您的位置:首页 > 其它

hibernate中把查询出来的集合封装为对象集合

2017-09-01 11:00 435 查看
public static List objectToList(List obj, Class clazz) throws Exception {
List list = new ArrayList();
for (Object result : obj) {
int i = 0;
// 获取结果集中每条记录的数据
Object[] values = (Object[]) result;
// 通过对象属性进行数据注入
Field[] f = clazz.getDeclaredFields();
Object o = clazz.newInstance();
for (Field field : f) {
char c = field.getName().charAt(0);
c -= 32;
String mname = c + field.getName().substring(1);
mname = "set" + mname;
Class<?> type = field.getType();
Method md = clazz.getMethod(mname, type);
if (i < values.length) {
String value = values[i].toString().trim();

if (type == String.class) {
md.invoke(o, values[i] != null ? value
: null);

} else{

if (type == Integer.class) {
md.invoke(o,Integer.valueOf(value));

} else if (type == Date.class) {
DateTimeFormat format = (field
.getAnnotation(DateTimeFormat.class));
SimpleDateFormat sdf = new SimpleDateFormat(
format.pattern());
md.invoke(o,sdf.parse(value) );

} else if (type == BigDecimal.class) {
md.invoke(o, new BigDecimal(value));

} else if (type == Long.class) {
md.invoke(o,Long.parseLong(value));

} else if (type == Short.class) {
md.invoke(o,Short.parseShort(value));

}
}
}
i++;
}
list.add(o);
}
return list;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: