日期:2014-05-20 浏览次数:20807 次
public class Query<T> { private DBUtil db = DBUtil.getInstance(); private List<T> list = null; private int totleCount = -1; private Class<T> entityClass; private String sql = null; @SuppressWarnings("unchecked") public Query(String sql) { this.entityClass = (Class<T>) ((ParameterizedType) getClass() .getGenericSuperclass()).getActualTypeArguments()[0]; this.sql = sql; this.list = excute(sql); } public int getCount() { return totleCount; } public List<T> getGridData(int start, int size) { if (start + size > totleCount) { size = totleCount - start; } return list.subList(start, start + size); } public List<T> getQueryData() { return list; } public List<T> excute(String sql) { ArrayList<T> list = null; Statement stm = db.getStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet rst = null; try { rst = stm.executeQuery(sql); rst.last(); totleCount = rst.getRow(); rst.beforeFirst(); list = new ArrayList<T>(totleCount); while (rst.next()) { ResultSetMetaData metaData = rst.getMetaData(); T t = entityClass.newInstance(); for (int j = 1; j <= metaData.getColumnCount(); j++) { String name = metaData.getColumnName(j); try { Field field = entityClass.getDeclaredField(name .substring(0, 1).toLowerCase() + name.substring(1)); Method method = entityClass.getMethod("set" + name.substring(0, 1).toUpperCase() + name.substring(1), field.getType()); String type = field.toGenericString(); if (type.contains("java.lang.String")) { method.invoke(t, rst.getString(name)); } else if (type.contains("java.lang.Integer")) { method.invoke(t, rst.getInt(name)); } else if (type.contains("java.lang.Double")) { method.invoke(t, rst.getDouble(name)); } else if (type.contains("java.sql.Date")) { method.invoke(t, rst.getDate(name)); } else if (type.contains("java.sql.Timestamp")) { method.invoke(t, rst.getTimestamp(name)); } } catch (NoSuchFieldException e) { /* * System.out.println("找不到字段" + name.substring(0, * 1).toLowerCase() + name.substring(1) + ",将忽略处理。"); */ } } list.add(t); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { db.freeResource(stm, rst); } return list; } }