import java.lang.reflect.Field; import java.lang.reflect.Method; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.Date; import java.util.List; public class BasicDao { private static Connection con = null; private static PreparedStatement ps = null; private static ResultSet rs = null; public static <T> List<T> selectAll(Class<T> clazz, String sql, Object parameter) { List<T> result = new ArrayList<T>(); // 遍历parameter的所有属性和值作为参数 Field[] paramField = parameter.getClass().getDeclaredFields(); for (Field pf : paramField) { try { if (pf.getType() == String.class) { if (pf.get(parameter) != null) { sql = sql.replace("/*" + pf.getName() + "*/", "'" + pf.get(parameter).toString() + "'"); } } else { if (pf.get(parameter) != null) { sql = sql.replace("/*" + pf.getName() + "*/", pf.get(parameter).toString()); } } System.out.println(pf.getName() + ":" + pf.get(parameter)); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } try { con = DBConnection.ConnectDB(); ps = con.prepareStatement(sql); System.out.println("[sql]:" + ps.toString().substring(ps.toString().indexOf(" "))); rs = ps.executeQuery(); while (rs.next()) { T entity; try { entity = clazz.newInstance(); } catch (Exception e) { e.printStackTrace(); return result; } Field[] entityFiled = clazz.getFields(); int fieldCount = 0; for (Field ef : entityFiled) { // 根据字段取出对应set方法赋值 Method m; try { m = entity.getClass().getMethod( "set" + ef.getName().substring(0, 1).toUpperCase() + ef.getName().substring(1), ef.getType()); if (ef.getType() == Integer.class) { m.invoke(entity, rs.getInt(++fieldCount)); } else if (ef.getType() == Long.class) { m.invoke(entity, rs.getLong(++fieldCount)); } else if (ef.getType() == Double.class) { m.invoke(entity, rs.getDouble(++fieldCount)); } else if (ef.getType() == Date.class) { m.invoke(entity, rs.getDate(++fieldCount)); } else if (ef.getType() == String.class) { m.invoke(entity, rs.getString(++fieldCount)); } // TODO } catch (Exception e) { e.printStackTrace(); return result; } } result.add(entity); } } catch (Exception e) { e.printStackTrace(); } return result; } }
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。