hibernate sql 对象转java对象

修改了一下,增加类型转换。用到了apache的beanutils工具包。

  1. public static <T> List<T> getEntityObjectListByFullSql(
  2. final String fullSql, final Class<T> clzz) throws Exception {
  3. return getHibernateTemplate().execute(
  4. new HibernateCallback<List<T>>() {
  5. @Override
  6. public List<T> doInHibernate(Session session)
  7. throws HibernateException, SQLException {
  8. SQLQuery sqlQuery = session.createSQLQuery(fullSql);
  9. sqlQuery.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);
  10. @SuppressWarnings("unchecked")
  11. List<Map<String, Object>> list = (List<Map<String, Object>>) sqlQuery
  12. .list();
  13. if (CollectionUtils.isEmpty(list)) {
  14. return null;
  15. }
  16. List<T> result = new ArrayList<T>();
  17. try {
  18. PropertyDescriptor[] props = Introspector
  19. .getBeanInfo(clzz).getPropertyDescriptors();
  20. for (Map<String, Object> map : list) {
  21. T t = clzz.newInstance();
  22. for (Entry<String, Object> entry : map
  23. .entrySet()) {
  24. String attrName = entry.getKey()
  25. .toLowerCase();
  26. for (PropertyDescriptor prop : props) {
  27. if (!attrName.equals(prop.getName())) {
  28. continue;
  29. }
  30. Method method = prop.getWriteMethod();
  31. Object value = entry.getValue();
  32. if (value != null) {
  33. value = ConvertUtils.convert(value,
  34. prop.getPropertyType());
  35. }
  36. method.invoke(t, value);
  37. }
  38. }
  39. result.add(t);
  40. }
  41. } catch (Exception e) {
  42. throw new RuntimeException(e);
  43. }
  44. return result;
  45. }
  46. });
  47. }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值