Generic을 이용해서 가져오기

 

HomeController

	// 데이터 조회하기 (전체 조회)
	@RequestMapping(value = "/select", method = RequestMethod.GET)
	public String select(Locale locale, Model model) {		
		DB db = new DB<Student>(".../student.db", "student");
		
		if (db.open()) {
			try {
				ArrayList<Student> resultData = db.selectData(new Student());
				model.addAttribute("htmlString", (new Student()).toHtmlString(resultData));	// Student()를 인스턴스화 해 새 객체로 만든다.
			} catch (Exception e) {
				e.printStackTrace();
				model.addAttribute("htmlString", "데이터를 조회를 할 수 없습니다.");
			}
			
			db.close();
		} else {
			model.addAttribute("htmlString", "DB파일을 사용할 수 없습니다.");
		}
		
		return "select";
	}

 

select.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<table>
${htmlString }
</table>
</body>
</html>

 

 

기존과 다른 점은 기존에는 매번 클래스가 달라질 때마다 DB를 수정했지만, 이제는 DB는 하나로 모두 사용할 수 있도록 반응형으로 작동하게 두고, Student 클래스를 거기게 맞게 만들어줄거다.

DB

	// Step 3. select 쿼리 실행
	public ArrayList<T> selectData(T t) {
		Class<?> dataClass = t.getClass();
		Field[] dataClassFields = dataClass.getDeclaredFields();
		
		String query = "SELECT * FROM " + this.tableName;
		ArrayList<T> resultDataSet = new ArrayList<T>();
				
		try {
			Statement statement = this.connection.createStatement();
			ResultSet result = statement.executeQuery(query);
			while(result.next()) {
				T rowData = (T)dataClass.getDeclaredConstructor().newInstance();	// unknown 클래스를 가지고 객체를 생성하는 방법.
				
				// for each를 이용해 
				for (Field field: dataClassFields) {	// Student.java의 내용을 한 줄씩 읽는다.
					// Step 1. 각 라인을 each로 읽어온다.
					String fieldName = field.getName();	// dataClassFields에서 각각 field(each)로 읽어온다... name, middleScore, finalScore
					String fieldType = field.getType().toString();	// 위와 마찬가지로 field(each)로 읽어온다... String, int, int
						
					if (fieldType.matches("(int|short)")) {
						field.setInt(rowData, result.getInt(fieldName));
					} else if (fieldType.matches("(long)")) {
						field.setLong(rowData, result.getLong(fieldName));
					} else if (fieldType.matches("(float|double)")) {
						field.setDouble(rowData, result.getDouble(fieldName));
					} else if (fieldType.matches(".*String")) {
						field.set(rowData, result.getString(fieldName));
					}
				}
				resultDataSet.add(rowData);
			}
			result.close();
			statement.close();
			
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultDataSet;		
 	}
	

 

Student.java

	public String toHtmlString(ArrayList<?> students) {
		String htmlText = "";
		for (int i = 0; i < students.size(); i++) {
			htmlText = htmlText + "<tr>";
			htmlText = htmlText + "<td>" + ((Student)students.get(i)).idx + "</td>";
			htmlText = htmlText + "<td>" + ((Student)students.get(i)).name + "</td>";
			htmlText = htmlText + "<td>" + ((Student)students.get(i)).middleScore + "</td>";
			htmlText = htmlText + "<td>" + ((Student)students.get(i)).finalScore + "</td>";
			htmlText = htmlText + "</tr>";
		}
		return htmlText;
	}

 

만약 이를 for each로 표현하면

	public String toHtmlString(ArrayList<?> resultDataSet) {
		String htmlText = "";
		for (Object student : resultDataSet) {
			htmlText = htmlText + "<tr>";
			htmlText = htmlText + "<td>" + ((Student)student).idx + "</td>";
			htmlText = htmlText + "<td>" + ((Student)student).name + "</td>";
			htmlText = htmlText + "<td>" + ((Student)student).middleScore + "</td>";
			htmlText = htmlText + "<td>" + ((Student)student).finalScore + "</td>";
			htmlText = htmlText + "</tr>";
		}
		return htmlText;
	}

 

다시 한 번 이것을 Object 대신 Generic을 이용해 타입을 지정해주면

	public String toHtmlString(ArrayList<Student> objects) {
		String htmlText = "";
		for (Student each : objects) {
			htmlText = htmlText + "<tr>";
			htmlText = htmlText + "<td>" + each.idx + "</td>";
			htmlText = htmlText + "<td>" + each.name + "</td>";
			htmlText = htmlText + "<td>" + each.middleScore + "</td>";
			htmlText = htmlText + "<td>" + each.finalScore + "</td>";
			htmlText = htmlText + "</tr>";
		}
		return htmlText;
	}

 

 

 

+ Recent posts