java 反射写的 通用DAO 类

最近 学习 反射,又在 做一个 web 网站,为了 减少代码,代码重用写了这个dao,效率,没有 每一个表写一个 dao 快。

 

不知道,这样写是否有用,希望大家,多多给予 指正(代码中的 不足,以及对这个 dao的 用处)

 

//DAO.java package com.dreaming.util; import java.util.ArrayList; import java.util.LinkedHashMap; public interface DAO { /** * 获取总记录总数 * * @param entityClass * 实体类 * @return */ public long getCount(Class entityClass); public long getCount(Class entityClass, String wherejpql, Object[] queryParams); /** * 保存实体 * * @param entity */ public void save(Object entity); /** * 更新 * * @param obj */ public void update(Object entity,String[] primaryKeys); public void update(Object entity,String primaryKey); /** * 删除单个 * @param * @param entityClass * @param primaryKeys * @param entityid */ public void delete(Class entityClass, String primaryKeys,Object entityid); public void delete(Class entityClass, String[] primaryKeys,Object[] entityid); public void deletes(Class entityClass, String primaryKeys,Object[] entityids); /** * 删除数组 * @param * @param entityClass * @param primaryKeys 数据表 主键数组 * @param entityids 主键值 */ public void deletes(Class entityClass, String[] primaryKeys,Object[][] entityids); /** * 得到实体 * * @param * @param entityClass * 实体类 * @param entityId * 实体id * @return */ public T find(Class entityClass, String primaryKey,Object entity); /** * 获取分页数据 * * @param * @param entityClass * 实体类 * @param firstindex * 开始索引 * @param maxresult * 需要获取的记录数 * @return */ public ArrayList getScrollData(Class entityClass, int firstindex, int maxresult, String wherejpql, Object[] queryParams, LinkedHashMap orderby); public ArrayList getScrollData(Class entityClass, int firstindex, int maxresult, String wherejpql, Object[] queryParams); public ArrayList getScrollData(Class entityClass, int firstindex, int maxresult, LinkedHashMap orderby); public ArrayList getScrollData(Class entityClass, int firstindex, int maxresult); public ArrayList getScrollData(Class entityClass); /** * 关闭数据库 连接 * */ public void closeConnection(); } //DaoSupport.java package com.dreaming.util; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.LinkedHashMap; public class DaoSupport implements DAO { private Connection conn = null; private PreparedStatement psmt = null; private ResultSet rs = null; public DaoSupport() { conMysql con = new conMysql(); conn = con.getConnection(); } public void delete(Class entityClass, String[] primaryKeys, Object[] entityid) { // TODO Auto-generated method stub this.deletes(entityClass, primaryKeys, new Object[][] { entityid }); } public void deletes(Class entityClass, String[] primaryKeys, Object[][] entityids) { // TODO Auto-generated method stub StringBuffer sql = new StringBuffer("delete from "); sql.append(this.getTable(entityClass)).append(" where "); for (String primaryKey : primaryKeys) { sql.append(primaryKey).append("=").append("?").append(" and "); } sql.delete(sql.length() - 5, sql.length()); System.out.println(sql); try { psmt = conn.prepareStatement(sql.toString()); for (Object[] entityid : entityids) { for (int i = 0; i < primaryKeys.length; i++) { psmt.setString(i + 1, String.valueOf(entityid[i])); } psmt.executeUpdate(); } if (rs != null) { rs.close(); } if (psmt != null) { psmt.close(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if (rs != null) { rs.close(); } if (psmt != null) { psmt.close(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public long getCount(Class entityClass) { return this.getCount(entityClass, null, null); } public long getCount(Class entityClass, String wherejpql, Object[] queryParams) { long count = 0; try { psmt = conn.prepareStatement("selcet count(*) from " + this.getTable(entityClass) + (wherejpql == null ? "" : " where " + wherejpql)); if (queryParams != null) { for (int i = 0; i < queryParams.length; i++) { psmt.setString(i + 1, String.valueOf(queryParams[i])); } } rs = psmt.executeQuery(); rs.next(); count = rs.getLong(1); if (rs != null) { rs.close(); } if (psmt != null) { psmt.close(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if (rs != null) { rs.close(); rs = null; } if (psmt != null) { psmt.close(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return count; } public T find(Class entityClass, String primaryKey, Object entity) { StringBuffer sql = new StringBuffer("select * from "); sql.append(this.getTable(entityClass)).append(" where ").append( primaryKey).append("=").append("'").append( String.valueOf(entity)).append("'"); Method[] methods = entityClass.getDeclaredMethods(); T obj = null; System.out.println(sql); try { psmt = conn.prepareStatement(sql.toString()); rs = psmt.executeQuery(); while (rs.next()) { try { obj = entityClass.newInstance(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } for (Method method : methods) { // System.out.println(method.getName().matches("/w")); String methodName = method.getName(); if (methodName.startsWith("set")) { String column = this.getColumn(methodName); if (rs.getString(column) != null) { Object[] objs = this.findOutParamValue(rs .getString(column), method); try { method.invoke(obj, objs); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return obj; } /** * 查询出,与实体entity 具有相同属性值的 项 * @param * @param entityClass * @param entity * @return */ public ArrayList finds(Class entityClass, Object entity) { ArrayList arraylist = new ArrayList(); Method[] methods = entity.getClass().getDeclaredMethods(); StringBuffer sql = new StringBuffer("select * from "); sql.append(this.getTable(entityClass)).append(" where "); for (Method method : methods) { if (method.getName().startsWith("get")) { Object[] args = new Object[] {}; try { Object values = method.invoke(entity, args); if (values != null) { String column = this.getColumn(method.getName()); sql.append(column).append("="); // 为字符串的时候,添加'' if (values.getClass().getSimpleName().equals("String")) { sql.append("'").append(String.valueOf(values)) .append("'").append(" and "); } else { sql.append(String.valueOf(values)).append(" and "); } } } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } sql.delete(sql.length() - 5, sql.length()); System.out.println(sql); T obj = null; try { psmt = conn.prepareStatement(sql.toString()); rs = psmt.executeQuery(); while (rs.next()) { try { obj = entityClass.newInstance(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } for (Method method : methods) { // System.out.println(method.getName().matches("/w")); String methodName = method.getName(); if (methodName.startsWith("set")) { String column = this.getColumn(methodName); if (rs.getString(column) != null) { Object[] objs = this.findOutParamValue(rs .getString(column), method); try { method.invoke(obj, objs); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } arraylist.add(obj); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return arraylist; } public ArrayList getScrollData(Class entityClass, int firstindex, int maxresult, LinkedHashMap orderby) { // TODO Auto-generated method stub return this.getScrollData(entityClass, firstindex, maxresult, null, null, orderby); } public ArrayList getScrollData(Class entityClass, int firstindex, int maxresult, String wherejpql, Object[] queryParams, LinkedHashMap orderby) { ArrayList arraylist = new ArrayList(); Method[] methods = entityClass.getDeclaredMethods(); String limit = ""; if (firstindex != -1 && maxresult != -1) limit = " limit " + firstindex + "," + maxresult; try { psmt = conn.prepareStatement("select * from " + getTable(entityClass) + (wherejpql == null ? "" : " where " + wherejpql) + buildOrderby(orderby) + limit); if (queryParams != null) { for (int i = 0; i < queryParams.length; i++) { psmt.setString(i + 1, String.valueOf(queryParams[i])); } } rs = psmt.executeQuery(); while (rs.next()) { T obj = null; try { obj = entityClass.newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } for (Method method : methods) { // System.out.println(method.getName().matches("/w")); String methodName = method.getName(); if (methodName.startsWith("set")) { String column = this.getColumn(methodName); if (rs.getString(column) != null) { Object[] objs = this.findOutParamValue(rs .getString(column), method); try { method.invoke(obj, objs); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } } } arraylist.add(obj); } } catch (SQLException e) { e.printStackTrace(); } finally { try { if (rs != null) { rs.close(); rs = null; } if (psmt != null) { psmt.close(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return arraylist; } public ArrayList getScrollData(Class entityClass, int firstindex, int maxresult, String wherejpql, Object[] queryParams) { // TODO Auto-generated method stub return this.getScrollData(entityClass, firstindex, maxresult, wherejpql, queryParams, null); } public ArrayList getScrollData(Class entityClass, int firstindex, int maxresult) { // TODO Auto-generated method stub return this.getScrollData(entityClass, firstindex, maxresult, null, null, null); } public ArrayList getScrollData(Class entityClass) { return this.getScrollData(entityClass, -1, -1, null, null, null); } public void save(Object entity) { Method[] methods = entity.getClass().getMethods(); String table = this.getTable(entity.getClass()); StringBuffer sql = new StringBuffer("insert into ").append(table); StringBuffer sql1 = new StringBuffer("("); StringBuffer sql2 = new StringBuffer("("); for (Method method : methods) { if (method.getName().startsWith("get") && (!method.getName().equals("getClass"))) { Object[] args = new Object[] {}; try { Object values = method.invoke(entity, args); if (values != null) { String column = this.getColumn(method.getName()); sql1.append(column).append(","); // 为字符串的时候,添加'' if (values.getClass().getSimpleName().equals("String")) { sql2.append("'").append(String.valueOf(values)) .append("'").append(","); } else { sql2.append(String.valueOf(values)).append(","); } } } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } } sql1.deleteCharAt(sql1.length() - 1).append(")"); sql2.deleteCharAt(sql2.length() - 1).append(")"); sql.append(" ").append(sql1).append(" values").append(sql2); System.out.println(sql); try { psmt = conn.prepareStatement(sql.toString()); psmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (rs != null) { rs.close(); rs = null; } if (psmt != null) { psmt.close(); } } catch (SQLException e) { e.printStackTrace(); } } } public void update(Object entity, String[] primaryKeys) { StringBuffer wheresql = new StringBuffer(" where "); StringBuffer sql0 = new StringBuffer(" "); Field[] fields = entity.getClass().getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); // Class Type = field.getType(); Object value = null; try { // value = Type.cast(field.get(entity)); 强制类型转换 value = field.get(entity); if ((!field.getName().equals("primaryKeys")) && value != null) { if (field.getType().getSimpleName().equals("String")) { sql0.append(field.getName()).append("=").append("'") .append(String.valueOf(value)).append("'") .append(","); } else { sql0.append(field.getName()).append("=").append( String.valueOf(value)).append(","); } } for (String primaryKey : primaryKeys) { if (field.getName().endsWith(primaryKey) && (value != null)) { if (field.getType().getSimpleName().equals("String")) { wheresql.append(primaryKey).append("=").append("'") .append(String.valueOf(value)).append("' ") .append("and"); } else { wheresql.append(primaryKey).append("=").append( String.valueOf(value)).append(" and "); } } } } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } wheresql.delete(wheresql.length() - 5, wheresql.length()); String table = this.getTable(entity.getClass()); StringBuffer sql = new StringBuffer("update ").append(table).append( " set "); sql.append(sql0).deleteCharAt(sql.length() - 1).append(wheresql); System.out.println(sql); try { psmt = conn.prepareStatement(sql.toString()); psmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (rs != null) { rs.close(); rs = null; } if (psmt != null) { psmt.close(); } } catch (SQLException e) { e.printStackTrace(); } } } /** * 转换为对应类型的值 * * @param param * @param method * @return */ private Object[] findOutParamValue(String param, Method method) { Class[] params = method.getParameterTypes(); Object[] objs = new Object[params.length]; for (int i = 0; i < params.length; i++) { // System.out.println(params.length); // System.out.println(param); if (params[i] == String.class) { objs[i] = param; } else if (params[i] == Integer.TYPE) { // int temp = Integer.parseInt(param); objs[i] = new Integer(param); } else if (params[i] == Short.TYPE) { objs[i] = new Short(param); } else if (params[i] == Float.TYPE) { objs[i] = new Float(param); } else if (params[i] == Double.TYPE) { objs[i] = new Double(param); } else if (params[i] == Boolean.TYPE) { objs[i] = new Boolean(param); } else if (params[i] == Long.TYPE) { objs[i] = new Long(param); } } return objs; } /** * 通过get or set 方法 得到数据表列名 * * @param name * @return */ private String getColumn(String name) { String newname = name.substring(3); if (newname.matches("//w[A-Z].*")) { return newname; } else { char[] temp = newname.toCharArray(); if ('A' <= temp[0] && temp[0] <= 'Z') { temp[0] = (char) ((int) temp[0] + 32); } return new String(temp); } } /** * 得到表名 * * @param entityClass * @return */ private String getTable(Class entityClass) { String entityName = entityClass.getSimpleName(); return entityName.substring(0, entityName.length() - 2); } /** * 组装order by语句 * * @param orderby * @return */ protected String buildOrderby(LinkedHashMap orderby) { StringBuffer orderbyql = new StringBuffer(""); if (orderby != null && orderby.size() > 0) { orderbyql.append(" order by "); for (String key : orderby.keySet()) { orderbyql.append(key).append(" ").append(orderby.get(key)) .append(","); } orderbyql.deleteCharAt(orderbyql.length() - 1); } return orderbyql.toString(); } public void closeConnection() { if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } // 强制类型转换 // public static T cast(Class clazz, Object obj) { // return clazz.cast(obj); // } public void update(Object entity, String primaryKey) { this.update(entity, new String[] { primaryKey }); } public void delete(Class entityClass, String primaryKeys, Object entityid) { this.delete(entityClass, new String[] { primaryKeys }, new Object[] { entityid }); } public void deletes(Class entityClass, String primaryKeys, Object[] entityids) { this.delete(entityClass, new String[] { primaryKeys }, entityids); } } //测试用 voardVO.java package com.dreaming.vo; public class boardVO { // public String[] primaryKeys = {"boardID","boardRootID"}; // public String primaryKeys = "boardID"; private Integer boardID; // 模块ID private String boardType; //varchar(30) not null, -- 模块类型 private String boardName; //varchar(30) not null, -- 模块名 private Integer boardRootID; //int(3) DEFAULT 0, -- 父节点 private Integer boardOrders; //int(3) DEFAULT 0, -- 模块排序 private String boardInfo; //varchar(600), -- 模块信息 public boardVO(){ } public boardVO(String boardType,String boardName,int boardRootID,String boardInfo){ this.boardType = boardType; this.boardName = boardName; this.boardRootID = boardRootID; this.boardInfo = boardInfo; } public String getBoardInfo() { return boardInfo; } public void setBoardInfo(String boardInfo) { this.boardInfo = boardInfo; } public String getBoardName() { return boardName; } public void setBoardName(String boardName) { this.boardName = boardName; } public Integer getBoardOrders() { return boardOrders; } public void setBoardOrders(int boardOrders) { this.boardOrders = boardOrders; } public Integer getBoardRootID() { return boardRootID; } public void setBoardRootID(int boardRootID) { this.boardRootID = boardRootID; } public String getBoardType() { return boardType; } public void setBoardType(String boardType) { this.boardType = boardType; } public Integer getBoardID() { return boardID; } public void setBoardID(int boardID) { this.boardID = boardID; } }

 

 

你可能感兴趣的:(java 反射写的 通用DAO 类)