您好,登錄后才能下訂單哦!
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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。