Hibernate Tips is a series of posts in which I describe a quick and easy solution for common Hibernate questions. If you have a question you like me to answer, please leave a comment below.
My query is too complex for JPQL, and I have to use a native query. What is the easiest way to map the result of the query to a POJO?
Don’t want to read? You can watch it here!
JPA supports @SqlResultSetMappings which you can use to map the query result to a POJO. The following code snippet shows an example of such a mapping.
The @ConstructorResult annotation defines a constructor call of the BookValue class. The @ColumnResult annotations define how the columns of the result shall be mapped to the parameters of the constructor. In this example, Hibernate will perform a constructor call with the value of the title column as the first and the value of the date column as the second parameter.
When you provide the name of the @SqlResultSetMapping as the second parameter to the createNativeQuery method, Hibernate will apply the mapping to the query result. You can use it to map the results of all queries that return at least the parameters defined by the @ColumnResult annotations.
Get this Hibernate Tip as a printable PDF!Join the free Thoughts on Java Library to get access to lots of member-only content, like a printable PDF for this post, lots of cheat sheets and 2 ebooks about Hibernate.
@SqlResultSetMappings are a powerful feature which allow you to define complex mappings for native query results. You can read more about native queries and @SqlResultSetMappings in my “Native Queries with Hibernate” ebook which you can download from the free Thoughts on Java Library.
Hibernate Tips Book
It gives you more than 70 ready-to-use recipes for topics like basic and advanced mappings, logging, Java 8 support, caching and statically and dynamically defined queries.
Get it now as a paperback, ebook or PDF.