ORM原理:
static List<Object> getObjects(String sql, Class clazz)
throws SQLException, Exception, IllegalAccessException,
InvocationTargetException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection();
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
String[] colNames = getColNames(rs);
List<Object> objects = new ArrayList<Object>();
Method[] ms = clazz.getMethods();
while (rs.next()) {
Object object = clazz.newInstance();
for ( int i = 0; i < colNames.length; i++) {
String colName = colNames[i];
String methodName = "set" + colName;
// Object value = rs.getObject(colName);
// try {
// Method m = clazz
// .getMethod(methodName, value.getClass());
// if (m != null)
// m.invoke(object, value);
// } catch (NoSuchMethodException e) {
// e.printStackTrace();
// //
// }
for (Method m : ms) {
if (methodName.equals(m.getName())) {
m.invoke(object, rs.getObject(colName));
break;
}
}
objects.add(object);
}
}
return objects;
} finally {
JdbcUtils.free(rs, ps, conn);
}
}
private static String[] getColNames(ResultSet rs) throws SQLException {
ResultSetMetaData rsmd = rs.getMetaData();
int count = rsmd.getColumnCount();
String[] colNames = new String[count];
for ( int i = 1; i <= count; i++) {
colNames[i - 1] = rsmd.getColumnLabel(i);
}
return colNames;
}
throws SQLException, Exception, IllegalAccessException,
InvocationTargetException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection();
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
String[] colNames = getColNames(rs);
List<Object> objects = new ArrayList<Object>();
Method[] ms = clazz.getMethods();
while (rs.next()) {
Object object = clazz.newInstance();
for ( int i = 0; i < colNames.length; i++) {
String colName = colNames[i];
String methodName = "set" + colName;
// Object value = rs.getObject(colName);
// try {
// Method m = clazz
// .getMethod(methodName, value.getClass());
// if (m != null)
// m.invoke(object, value);
// } catch (NoSuchMethodException e) {
// e.printStackTrace();
// //
// }
for (Method m : ms) {
if (methodName.equals(m.getName())) {
m.invoke(object, rs.getObject(colName));
break;
}
}
objects.add(object);
}
}
return objects;
} finally {
JdbcUtils.free(rs, ps, conn);
}
}
private static String[] getColNames(ResultSet rs) throws SQLException {
ResultSetMetaData rsmd = rs.getMetaData();
int count = rsmd.getColumnCount();
String[] colNames = new String[count];
for ( int i = 1; i <= count; i++) {
colNames[i - 1] = rsmd.getColumnLabel(i);
}
return colNames;
}
本文转自 tianya23 51CTO博客,原文链接:http://blog.51cto.com/tianya23/246904,如需转载请自行联系原作者