public <T> T getInstance(Connection conn, Class<T> clazz, String sql, Object... args) { PreparedStatementps=null; ResultSetrs=null; try { ps = conn.prepareStatement(sql); for (inti=0; i < args.length; i++) { ps.setObject(i + 1, args[i]); }
rs = ps.executeQuery(); // get metadata ResultSetMetaDatametaData= rs.getMetaData(); // get number of colums from ResultSetMetaData intcolumnCount= metaData.getColumnCount(); if (rs.next()) { Tt= clazz.newInstance(); // The clazz must have a constructor without parameters for (inti=0; i < columnCount; i++) { // get column value ObjectcolumnValue= rs.getObject(i + 1); // get column name for each column // column name: getColumnName(); // alias name: getColumnLabel(); StringcolumnName= metaData.getColumnLabel (i + 1);
// using reflect to set values for the Class Fieldfield= clazz.getDeclaredField(columnName); field.setAccessible(true); field.set(t, columnValue); } return t; } } catch (Exception e) { e.printStackTrace(); } finally { JDBCUtils.closeResource(null, ps, rs); } returnnull; }
rs = ps.executeQuery(); // get metadata ResultSetMetaDatametaData= rs.getMetaData(); // get number of colums from ResultSetMetaData intcolumnCount= metaData.getColumnCount(); // create Set object ArrayList<T> list = newArrayList<T>(); while (rs.next()) { Tt= clazz.newInstance(); // The clazz must have a constructor without parameters for (inti=0; i < columnCount; i++) { // get column value ObjectcolumnValue= rs.getObject(i + 1); // get column name for each column // column name: getColumnName(); // alias name: getColumnLabel(); StringcolumnName= metaData.getColumnLabel (i + 1);
// using reflect to set values for the Class Fieldfield= clazz.getDeclaredField(columnName); field.setAccessible(true); field.set(t, columnValue); } list.add(t); } return list; } catch (Exception e) { e.printStackTrace(); } finally { JDBCUtils.closeResource(null, ps, rs); } returnnull; }