//用hibernate查询后的结果集直接转已有的对象
List list = session.createSQLQuery(sql.toString())
.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
Class[] cla = {对象A.class,对象B.class};//其中对象A extends 对象B
List result = ClassHelper.mapListToEntityList(list,cla);
ClassHelp类
public class ClassHelper{
/*map集合转对象集合 是否格式化NULL数据*/
public static List mapListToEntityList(List<Map<String, Object>> sourceList, Class[] classes,Boolean isFormat) throws InstantiationException, IllegalAccessException {
if(sourceList==null || sourceList.size()==0){
return null;
}
Map<String, Field> usedFields = getUsedFields(sourceList.get(0).keySet(), classes);
long l = System.currentTimeMillis();
Class clazz = classes[0];
List result = new ArrayList(sourceList.size());
Object entity;
Field field;
for (Map<String,Object> map : sourceList) {
entity = clazz.newInstance();
for (Map.Entry<String, Object> entry : map.entrySet()) {
if((field = usedFields.get(entry.getKey()))==null){
continue;
}
// System.out.println(entry.getKey()+"="+usedFields.get(entry.getKey())+"="+entry.getValue());
if(isFormat){
if(field.getType() == Double.class){
field.set(entity, Arith.doubleFormat(entry.getValue()));
}else if (field.getType() == Boolean.class) {
field.set(entity, entry.getValue()!=null && entry.getValue().equals(1));
}else if(field.getType() == String.class){
field.set(entity,Arith.strFormat(entry.getValue()));
}else {
field.set(entity,entry.getValue());
}
}else{
if(field.getType() == Double.class){
field.set(entity,(Double)(entry.getValue()));
}else if (field.getType() == Boolean.class) {
field.set(entity, entry.getValue()!=null && entry.getValue().equals(1));
}else if(field.getType() == String.class){
field.set(entity,(String)entry.getValue());
}else {
field.set(entity,entry.getValue());
}
}
}
result.add(entity);
}
System.out.println(System.currentTimeMillis()-l+"ms result.len="+result.size());
return result;
}
/**map集合转对象集合*/
public static List mapListToEntityList(List<Map<String, Object>> sourceList, Class[] classes) throws InstantiationException, IllegalAccessException {
return mapListToEntityList(sourceList, classes, true);
}
private static Map<String,Field> getUsedFields( Set<String> keys,Class[] classes) {
HashMap<String, Field> result = new HashMap<String, Field>();
List<Field> fields = getAllDeclaredField(classes);
for (String key : keys) {
for (Field field : fields) {
String lowerCase = field.getName().toLowerCase();
if(key.toLowerCase().equals(lowerCase)){
field.setAccessible(true);
result.put(key, field);
fields.remove(field);
break;
}
}
}
return result;
}
private static List<Field> getAllDeclaredField(Class[] classes) {
List<Field> result = new ArrayList<Field>();
for (Class clazz : classes) {
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
result.add(field);
}
}
return result;
}
}