Quantcast
Channel: getting result set into DTO with native SQL Query in Hibernate - Stack Overflow
Viewing all articles
Browse latest Browse all 2

Answer by Pascal Thivent for getting result set into DTO with native SQL Query in Hibernate

$
0
0

You could maybe use a result transformer. Quoting 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 ;)

References


Viewing all articles
Browse latest Browse all 2

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>