hibernate 里想将sql的结果转为对象,但是对象不想再.hb.xml里定义,可以考虑用 ResultTransformer
使用SQL Transformers
List resultWithAliasedBean = s.createSQLQuery(
"SELECT st.name as studentName, co.description as courseDescription " +
"FROM Enrolment e " +
"INNER JOIN Student st on e.studentId=st.studentId " +
"INNER JOIN Course co on e.courseCode=co.courseCode")
.addScalar("studentName")
.addScalar("courseDescription")
.setResultTransformer( Transformers.aliasToBean(StudentDTO.class))
.list();
StudentDTO dto =(StudentDTO) resultWithAliasedBean.get(0);
注意,如果不加上addScalar()调用的话,可能有些属性不会被设置值,因为他们可能是用大写字母返回的。
用Map
指定Transformers.ALIAS_TO_MAP就可以了,如下所示,你不必为了在需要记忆字段对应的位置,因为他们是map
List iter = s.createQuery(
"select e.student.name as studentName," +
" e.course.description as courseDescription" +
"from Enrolment as e")
.setResultTransformer( Transformers.ALIAS_TO_MAP )
.iterate();
String name = (Map)(iter.next()).get("studentName");
原文:http://swik.net/Hibernate/Hibernate+GroupBlog/Hibernate+3.2:+Transformers+for+HQL+and+SQL/cmxs
已有 0 人发表留言,猛击->> 这里<<-参与讨论
ITeye推荐