我有如下查询
select f.id, s.name, ss.name
from first f
left join second s on f.id = s.id
left join second ss on f.sId = ss.id
如果我可以使用 HQL,我会使用 HQL constructor syntax直接用结果集填充 DTO。 但是,由于 hibernate 不允许在没有关联的情况下进行左连接,因此我必须使用 native SQL 查询。
目前我正在以 JDBC 样式循环结果集并填充 DTO 对象。 有没有更简单的方法来实现它?
最佳答案
您也许可以使用结果转换器。报价 Hibernate 3.2: Transformers for HQL and SQL :
SQL Transformers
With native sql returning non-entity beans or Map's is often more useful instead of basic
Object[]
. With result transformers that is now possible.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);
Tip: the
addScalar()
calls were required on HSQLDB to make it match a property name since it returns column names in all uppercase (e.g. "STUDENTNAME"). This could also be solved with a custom transformer that search the property names instead of using exact match - maybe we should provide a fuzzyAliasToBean() method ;)
引用文献
- hibernate 引用指南
- Hibernate 的博客
关于java - 在 Hibernate 中使用 native SQL 查询将结果集放入 DTO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3937131/