/**
* 通过反射和泛型编写通用的查询
* @param clazz
* @param sql
* @param objects
* @return
* @throws Exception
*/
public <T> T getObject(Class<T> clazz,String sql,Object ...objects) throws Exception{
T entity = null;
Connection connection = C3p0Utils.newInstance().getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(sql);
for(int i=0;i<objects.length;i++){
preparedStatement.setObject(i+1, objects[i]);
}
ResultSet resultSet = preparedStatement.executeQuery();
ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
int columnCount = resultSetMetaData.getColumnCount();
Map<String,Object> map = new HashMap<String,Object>();
if(resultSet.next()){
for(int i=0;i<columnCount;i++){
String fieldName = resultSetMetaData.getColumnLabel(i+1);
Object fieldValue = resultSet.getObject(i+1);
map.put(fieldName, fieldValue);
}
}
System.out.println("map:"+map);
entity = clazz.newInstance();
for(Map.Entry<String, Object> entry : map.entrySet()){
String name = entry.getKey();
Object value = entry.getValue();
Method method = clazz.getMethod(toMethod(name), toClass(clazz, name));
method.invoke(entity, value);
}
return entity;
}
/**
* 将字段名转换为方法名
* @param name
* @return
*/
public String toMethod(String name){
return "set"+name.substring(0, 1).toUpperCase()+name.substring(1);
}
/**
* 获取指定字段的数据类型
* @param clazz
* @param name
* @return
* @throws Exception
*/
public Class toClass(Class clazz,String name) throws Exception{
Field field = clazz.getDeclaredField(name);
return field.getType();
}
转载于:https://blog.51cto.com/11147669/1905603