Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.lang.reflect.Method;
- import java.sql.ResultSet;
- import java.sql.ResultSetMetaData;
- import java.sql.SQLException;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- /**
- * ResultSet 결과를 자동으로 Bean에 Set 하고 난 뒤에
- * ArrayList 형태로 반환받음
- */
- public class BeanMapper implements RowMapper{
- private Class beanClass = null;
- private BeanMapper() {};
- public BeanMapper(Class beanClass) {
- if (beanClass == null) {
- new Exception (" 해당 클래스를 찾을 수가 없습니다.");
- }
- this.beanClass = beanClass;
- }
- public Object mapRow(ResultSet rs) throws SQLException {
- Object obj = null;
- List list = null;
- try {
- //컬럼정보를 가져옴
- ResultSetMetaData rsmd = rs.getMetaData();
- //컬럼개수
- int count = rsmd.getColumnCount();
- //Bean Class 의 instance를 생성함.
- obj = beanClass.newInstance();
- //method들을 가져옴
- Method[] method = beanClass.getMethods();
- HashMap methodMap = new HashMap();
- //method들의 이름을 key값으로 하여 map 형태로 저장함
- for (int i = 0; i < method.length; i++) {
- methodMap.put(method[i].getName(), method[i]);
- }
- //ResultSet 의 값을 Mapping 하기 위해..
- while (rs.next()){
- //List 형태로 반환하기 위해..
- list = new ArrayList();
- //컬럼 수 만큼 반복함
- for (int i = 1; i <= count; i++) {
- //SQL 문에서 익명 값을 가져옴 ( 이유는 Mapping을 좀더 수월히 하기 위해서임 )
- String columnName = rsmd.getColumnLabel(i);
- //setDocId 이런 형태로 만들기 위해서.. 즉 set+익명컬럼첫글자대문자+쭉...
- //카멜 명명법으로 컬럼명도 만들어야 쉽게 사용 가능하다.
- String setName = "set" + columnName.substring(0, 1).toUpperCase() + columnName.substring(1);
- try {
- // BeanClass의 메소드 명을 키값으로 만들었기 때문에 해당 클래스를 호출함.
- Method meth = (Method) methodMap.get(setName);
- // method 존재여부
- if (meth == null) {
- System.out.println("해당 메소드가 없습니다. 확인해주세요 : " + setName);
- } else {
- //method의 Type정보를 가져옴
- Class[] paramType = meth.getParameterTypes();
- Object value = null;
- //Type의 이름을 가져옴 ( ex-> java.util.Date => Date )
- //각 Type별로 rs.get? 해서 value에 담음..
- if (paramType[0].getSimpleName().equals("int")) {
- value = rs.getInt(i);
- } else if(paramType[0].getSimpleName().equals("Date")){
- value = rs.getDate(i);
- } else {
- value = rs.getString(i);
- }
- //메소드 실행
- meth.invoke(obj, new Object[] { value });
- }
- } catch (Exception e) {
- //어떤 컬럼에서 오류나는지 확인하기 위해 찍어봄..
- System.out.println(setName);
- e.printStackTrace();
- }
- }
- //리스트에 담음
- list.add(obj);
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- return list;
- }
- }
Add Comment
Please, Sign In to add comment