修改了一下,增加类型转换。用到了apache的beanutils工具包。
- public static <T> List<T> getEntityObjectListByFullSql(
- final String fullSql, final Class<T> clzz) throws Exception {
- return getHibernateTemplate().execute(
- new HibernateCallback<List<T>>() {
- @Override
- public List<T> doInHibernate(Session session)
- throws HibernateException, SQLException {
- SQLQuery sqlQuery = session.createSQLQuery(fullSql);
- sqlQuery.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);
- @SuppressWarnings("unchecked")
- List<Map<String, Object>> list = (List<Map<String, Object>>) sqlQuery
- .list();
- if (CollectionUtils.isEmpty(list)) {
- return null;
- }
- List<T> result = new ArrayList<T>();
- try {
- PropertyDescriptor[] props = Introspector
- .getBeanInfo(clzz).getPropertyDescriptors();
- for (Map<String, Object> map : list) {
- T t = clzz.newInstance();
- for (Entry<String, Object> entry : map
- .entrySet()) {
- String attrName = entry.getKey()
- .toLowerCase();
- for (PropertyDescriptor prop : props) {
- if (!attrName.equals(prop.getName())) {
- continue;
- }
- Method method = prop.getWriteMethod();
- Object value = entry.getValue();
- if (value != null) {
- value = ConvertUtils.convert(value,
- prop.getPropertyType());
- }
- method.invoke(t, value);
- }
- }
- result.add(t);
- }
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- return result;
- }
- });
- }