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. Is there a way to map the result of the query to managed entities?
Don’t want to read? You can watch it here!
If your query returns all columns that are mapped by an entity, you can tell Hibernate to map the result to a managed entity. Afterwards, you can use the entity in the same way as any other entity.
There are 2 options to define the mapping:
- You can use an implicit mapping if your query result uses the same column names as your entity mapping.
- You can create your own mapping if the column names do not match the entity mapping
The implicit mapping is easier to use and the better approach for most use cases. You only need to provide the class of the entity as the second parameter to the createNativeQuery method.
Explicit Mapping If the column names of your query result do not match the column names of your entity mapping, you have to define the mapping yourself. You can do this with a @SqlResultSetMapping which specifies the mapping for each entity attribute.
As you can see in the code snippet, the @SqlResultSetMapping requires a name and an @EntityResult annotation which defines the mapping to the entity.
You, therefore, need to specify the class of the entity and a set of @FieldResult annotation which define the mapping between the result set column and the entity attribute.
You can then use this mapping by providing its name as the 2nd parameter to the createNativeQuery method.
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.
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.