In the first post of this series, we had a look at some mapping definition between the query result and one entity. The mapping definitions got more complex in the second part, as we mapped the query result to multiple entities and handled additional columns.
In this post, we will have a look at the Constructor Result Mappings
introduced in JPA 2.1. This feature allows us to call the constructor of a value object with the result of the query, similar to the JPQL constructor expressions. This is often used, if we want to provide a specific view of our domain model to the client.
The example
Before we start, lets have a look at the entity model that we will use for the examples. If you read the
second part of this series, you are already familiar with the
Author and
Book entities. Both entities are quite simple. The
Author entity has an id, a version, a first name and a last name. The
Book entity has an id, a version, a title and a reference to the
Author. To avoid unnecessary complexity, each
Book was written by only one
Author.
As we want to map our query results to a value object, we need an additional class called
BookValue with an id, a version, a title and the name of the author.
I used
Wildfly 8.2 with
Hibernate 4.3.7 to test the examples in this series. But as these are standard JPA features, you should be able to use them with all other JPA 2.1 implementations, e.g. with the
GlassFish 4.1 application server which uses
EclipseLink.
You can find the source code on my
github account.
How to map to a value object
Selecting entities and returning a tree of objects to the caller is not always the best approach. The caller often needs only a subset of the provided information and a specific value object would be much more efficient. For these situations, JPQL supports constructor expressions that can be specified in the select part of the JPQL query and define the constructor call for each selected record.