본문 바로가기
개발자의 정보/Java & framework

DB 관련 프레임워크를 사용하지 않는 환경에서 DB 개발을 해야 한다.

by pastory 2020. 2. 1.

DB 관련 프레임워크를 사용하지 않는 환경에서 DB 개발을 해야 한다.

고전적인 방법으로 일일이 커넥션과 이것저것 관리 하기는 귀찮다.

 

그래서 급한대로 필요한 기능 몇 가지를 만들었다. 참고로 java1.4 버전 환경이다.

바쁘니까 설명은 나중에 시간날때.. 에효..

 

AutoRowMapper.java

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;
import java.util.Map;

import org.springframework.jdbc.core.RowMapper;

public class AutoRowMapper implements RowMapper {
        private Class targetClass = null;

        private AutoRowMapper() {};
       
        public AutoRowMapper(Class targetClass) {
               if (targetClass == null)
                      new RuntimeException("targetClass can't be null" );
               this.targetClass = targetClass;
       }
       
        public List getObjectMapList(ResultSet rs) throws SQLException {
              ArrayList list = new ArrayList();
              
               while (rs.next()) {
                     list.add(getMap(rs));
              }
              
               return list;
       }
       
        public Map getObjectMap(ResultSet rs) throws SQLException {
              Map map = null;
              
               if (rs.next()) {
                     map = getMap(rs);
              }
              
               return map;
       }

        public Map getMap(ResultSet rs) throws SQLException {
               return getMap(rs, false);
       }
       
        public Map getMap(ResultSet rs, boolean useConvert) throws SQLException {
              Map map = new HashMap();
              
              ResultSetMetaData rsmd = rs.getMetaData();
               int columnCnt = rsmd.getColumnCount();
              
               for (int i = 1; i <= columnCnt; i++) {
                     String columnName = rsmd.getColumnName(i);
                     columnName = columnName.toLowerCase();
                     
                      if (useConvert) {
                            while (columnName.indexOf("_" ) > -1) {
                                  columnName = convertString(columnName);
                           }
                     }
                     
                     map.put(columnName, rs.getObject(i));
              }
              
               return map;
       }
       
        public List getObjectList(ResultSet rs) throws SQLException {
              ArrayList list = new ArrayList();
              
               while (rs.next()) {
                     list.add(mapRow(rs));
              }
              
               return list;
       }
       
        public Object getObject(ResultSet rs) throws SQLException {
              Object obj = null;
              
               if (rs.next()) {
                     obj = mapRow(rs);
              }
              
               return obj;
       }
       
        public Object mapRow(ResultSet rs) throws SQLException {
               return mapRow(rs, 0, false);
       }
       
        public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
               return mapRow(rs, rowNum, false);
       }

        public Object mapRow(ResultSet rs, int rowNum, boolean useConvert) throws SQLException {
              Object o = null;
               try {
                     ResultSetMetaData rsmd = rs.getMetaData();
                      int columnCnt = rsmd.getColumnCount();
                     o = targetClass.newInstance();
                     Method[] method = targetClass.getMethods();
                     HashMap methMap = new HashMap();

                      for (int i = 0; i < method.length; i++) {
                           methMap.put(method[i].getName(), method[i]);
                     }

                      for (int i = 1; i <= columnCnt; i++) {
                           String columnName = rsmd.getColumnName(i);
                           columnName = columnName.toLowerCase();
                           
                            if (useConvert) {
                                   while (columnName.indexOf("_" ) > -1) {
                                         columnName = convertString(columnName);
                                  }
                           }
                           
                           String setterName = "set" + columnName.substring(0, 1).toUpperCase() + columnName.substring(1);
                           
                            try {
                                  Method meth = (Method) methMap.get(setterName);
                                   if (meth != null) {
                                         String rsVal = rs.getString(i);
                                         Class[] paramType = meth.getParameterTypes();
                                         Object value = rs.getObject(i);
                                         
                                          if (value != null) {
                                                 if (paramType[0].equals(Integer.TYPE )) {
                                                       value = new Integer(rsVal);
                                                } else if (paramType[0].equals(Float.TYPE )) {
                                                       value = new Float(rsVal);
                                                } else if (paramType[0].equals(Long.TYPE )) {
                                                       value = new Long(rsVal);
                                                } else {
                                                       value = rs.getString(i);
                                                }
                                                
                                                meth.invoke(o, new Object[] { value });
                                         }
                                  }
                           } catch (Exception e) {
                                  e.printStackTrace();
                           }
                     }
              } catch (Exception e) {
                     e.printStackTrace();
              }
               return o;
       }

        private String convertString(String str) {
              String tempStr = null;
               if (str.indexOf( "_") > -1) {
                      int index = str.indexOf("_" );
                      if (index != str.length() - 1) {
                           tempStr = str.substring(0, index) + str.substring(index + 1, index + 2).toUpperCase()
                                         + str.substring(index + 2);
                     } else {
                           tempStr = str.substring(0, index);
                     }
              } else {
                     tempStr = str;
              }
               return tempStr;
       }
}

 

GenericDAO.java

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import **.util.db.AutoRowMapper;
import **.util.db.ConnectionManager;

public class GenericDAO {
       
        protected ResultSet rs ;
        protected PreparedStatement pstmt ;
        protected Connection conn ;

        protected void close() {
               try { if (rs != null) rs.close(); } catch (Exception ex) {}
               try { if (pstmt != null) pstmt.close(); } catch (Exception ex) {}
               try { if (conn != null) ConnectionManager.returnConnection(conn ); } catch (Exception ex) {}
       }
       
        protected PreparedStatement setPstmt(PreparedStatement pstmt, Object[] args) throws SQLException {

               for (int i = 0; i < args.length; i++) {
                     Object obj = args[i];
                     
                     pstmt.setObject(i + 1, obj);
//                   if ( obj == null) {
//                          Int(i + 1, ((Integer) obj ).intValue());
//                   } else if ( obj instanceof Integer) {
//                         pstmt.setInt(i + 1, ((Integer) obj).intValue());
//                   } else if ( obj instanceof Float) {
//                         pstmt.setFloat(i + 1, ((Float) obj).floatValue());
//                   } else if ( obj instanceof Long) {
//                         pstmt.setLong(i + 1, ((Long) obj).longValue());
//                   } else {
//                         pstmt.setString(i + 1, obj.toString());
//                   }
              }
              
               return pstmt;
       }
       
        protected int save(String sql, Object[] args) {
               int result = 0;
              
               try {
                      conn = ConnectionManager. getConnection();

                      pstmt = conn.prepareStatement(sql);
                     setPstmt( pstmt, args);
                     
                     result = pstmt.executeUpdate();
              } catch (Exception e) {
                     e.printStackTrace();
              } finally {
                     close();
              }
              
               return result;
       }
       
        protected Object getData(String sql, Object[] args) {
              Object result = null;
              
               try {
                      conn = ConnectionManager. getConnection();

                      pstmt = conn.prepareStatement(sql);
                     setPstmt( pstmt, args);
                     
                      rs = pstmt.executeQuery();
                     
                      if ( rs.next()) {
                           result = rs.getObject(1);
                     }
              } catch (Exception e) {
                     e.printStackTrace();
              } finally {
                     close();
              }
              
               return result;
       }

        protected List getMapList(String sql, Object[] args) {
              
              List list = null;
              
               try {
                      conn = ConnectionManager. getConnection();

                      pstmt = conn.prepareStatement(sql);
                     setPstmt( pstmt, args);
                     
                      rs = pstmt.executeQuery();

                     AutoRowMapper arm = new AutoRowMapper(Map.class);
                     list = arm.getObjectMapList( rs);
                     
              } catch (Exception e) {
                     e.printStackTrace();
              } finally {
                     close();
              }
              
               return list;
       }
       
        protected Map getMap(String sql, Object[] args) {
              Map result = null;
              
               try {
                      conn = ConnectionManager. getConnection();

                      pstmt = conn.prepareStatement(sql);
                     setPstmt( pstmt, args);
                     
                      rs = pstmt.executeQuery();
                     
                     AutoRowMapper mapper = new AutoRowMapper(Map.class);
                     result = mapper.getObjectMap( rs);
              } catch (Exception e) {
                     e.printStackTrace();
              } finally {
                     close();
              }
              
               return result;
       }

       
        protected Object getObject(String sql, Object[] args, Class target) {
              
              Object result = null;
              
               try {
                      conn = ConnectionManager. getConnection();

                      pstmt = conn.prepareStatement(sql);
                     setPstmt( pstmt, args);
                     
                     System. out.println(sql);
                     System. out.print("params: [" );
                     
                      for (int i = 0; i < args.length; i++) {
                           System. out.println("\t\"" + args[i] + "\"");
                     }
                     System. out.println("]" );
                     
                      rs = pstmt.executeQuery();

                     AutoRowMapper mapper = new AutoRowMapper(target);
                     result = mapper.getObject( rs);
              } catch (Exception e) {
                     e.printStackTrace();
              } finally {
                     close();
              }
              
               return result;
       }
       
        protected List getObjectList(String sql, Object[] args, Class target) {
              
              List list = null;
              
               try {
                      conn = ConnectionManager. getConnection();

                      pstmt = conn.prepareStatement(sql);
                     setPstmt( pstmt, args);

                     System. out.println(sql);
                     System. out.print("params: [" );
                     
                      for (int i = 0; i < args.length; i++) {
                           System. out.println("\t\"" + args[i] + "\"");
                     }
                     System. out.println("]" );
                     
                      rs = pstmt.executeQuery();

                     AutoRowMapper arm = new AutoRowMapper(target);
                     list = arm.getObjectList( rs);
              } catch (Exception e) {
                     e.printStackTrace();
              } finally {
                     close();
              }
              
               return list;
       }
}

 

댓글