泛型BaseDAO

对于属性比较多的bean,如果不使用hibernate 或者ibatis等持久化解决方案,写查询函数时,单单将ResultSet 转换成Object就是一件很痛苦的事情,因此可以采用java反射机制做一个BaseDao,把ResultSet 映射到Object 的操作封装起来,简化了DAO的开发,
本文参照了[url]http://blog.csdn.net/cping1982/archive/2007/10/01/1808647.aspx
[/url]并且做了一点改进
public static String[][] proterty2Column = 
	    {{"member_id","memberId"},		
		{"name", "name"}};
	/**
	 * change the first char to upper case
	 * @param s
	 * @return
	 */
	private static String upperFirstChar(String s){
		char [] chars = s.toCharArray();
		chars[0] = Character.toUpperCase(chars[0]);
		return new String(chars);
	}
	/**
* ResultSet 映射成 Object
	 * @param clzz
	 * @param rs 
	 * @param obj
	 * @param fieldName
	 * @param varibleName
	 * @throws NoSuchMethodException
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 * @throws SQLException
	 * @throws NoSuchFieldException 
	 * @throws SecurityException 
	 */
    private void  mapResultSet2Object(ResultSet rs, Object obj, String propertyName,
 String columName) 
throws NoSuchMethodException, IllegalAccessException, 
InvocationTargetException, SQLException, 
SecurityException, NoSuchFieldException {
    	 Class < ? extends Object >clazz = obj.getClass();
         Class < ? extends Object >propertyType = clazz.getDeclaredField(propertyName).
getType();
       Method method = clazz.getDeclaredMethod("set"+ 
     upperFirstChar( propertyName ), new Class[] { propertyType });
       if (propertyType == String.class)
           method.invoke(obj, (Object [])new String[] 
{rs.getString( columName ) });
       else if (propertyType == int.class)
           method.invoke(obj, (Object [])new Integer[] 
{new Integer( rs.getInt( columName )) });
       else if (propertyType == float.class)
           method.invoke(obj, (Object [])new Float[] 
{new Float( rs.getFloat( columName )) });
       else if (propertyType == long.class)
           method.invoke(obj, (Object [])new Long[]
 {new Long( rs.getLong( columName )) });
       else if (propertyType == double.class)
           method.invoke(obj, (Object [])new Double[] 
{new Double( rs.getDouble( columName )) });
       else if(propertyType == Date.class){
    	   method.invoke(obj, (Object [])new Date[] 
{rs.getDate(columName)});
       }
   }
    /**
     * 单行查询
     * @param 
     * @param conn
     * @param sql
     * @param clazz
     * @param params
     * @return
     * @throws Exception
     */
    public  <T> T getItem(Connection conn, String sql, Class<T> clazz, 
  String params[])throws Exception{
    	PreparedStatement pstmt = null;
    	ResultSet rset = null;
    	T t  = null;
    	try {
    		pstmt = conn.prepareStatement(sql);
    		//set parameter 
               for(int i=0; i<params.length; i++){
    			pstmt.setString(i+1, (String)params[i]);
    		}
              rset = pstmt.executeQuery();
            if (rset.next()) {
                t =  clazz.newInstance();
    		for(int i=0; i< proterty2Column.length; i++) {
                	String propertyName = proterty2Column[i][1].trim();
                    String ColumnName = proterty2Column[i][0].trim();
                    mapResultSet2Object(rset, t, propertyName, ColumnName);
                }
            }
        } catch (Exception e) {
        	e.printStackTrace();
	    } finally {
	        DBUtil.closeAll(conn, pstmt, rset);
	    }
     return t;
    }

   /**
     * 多行查询
     * @param 
     * @param conn
     * @param sql
     * @param proterty2Column
     * @param clazz
     * @return
     * @throws Exception
     */
    public   <T> List <T> getItems(Connection conn, String sql, Class<T> clazz,  
String[] params) throws Exception{
    	if (proterty2Column.length == 0)
            return null;
    	PreparedStatement pstmt = null;
    	ResultSet rset = null;
    	List<T> list = new ArrayList<T>();
    	try {
    		pstmt = conn.prepareStatement(sql);
               for(int i=0; i<params.length; i++){
    			pstmt.setString(i+1, (String)params[i]);
    		}
    		rset = pstmt.executeQuery();
            while (rset.next()) {
    		for(int i=0; i< proterty2Column.length; i++) {
                	String propertyName = proterty2Column[i][1].trim();
                    String ColumnName = proterty2Column[i][0].trim();
                    fetchResult2Object(rset, obj, propertyName, ColumnName);
                }
                if( null == obj ) continue;
                list.add(obj);
            }
        } catch (Exception e) {
        	e.printStackTrace();
	    } finally {
	        DBUtil.closeAll(conn, pstmt, rset);
	    }
     return list;
    }

你可能感兴趣的:(DAO,sql,Hibernate,bean,ibatis)