Spring Data JPA Projection support for native queries

Thats where projections are needed.

Projections in simple terms is a way to create and populate DTO’s from database entities / models.

ExampleLet’s build the example considering a simple data model (referenced here) and a simple native query.

The Data ModelLet’s have a look at the Customer entity class:and Order entity:The Native QueryWe now define our “named-native-query” in the orm.

xml, the query lists all customers, whether they placed any order or not.

Notice the alias for every field in the select query.

This is important when we build the projections object.

The DTO’sNext let’s create an interface based projection class, which will act as the DTO.

The projections interface CustomerDetailsDTO has accessor methods that match all the properties of the select query being fetched.

Example: The native query being executed fetches the field “id” and assigns it to an alias “customerId”.

This alias exactly maps the accessor method getCustomerId() defined in the DTO.

Projection interfaces can also be used to compute new values by using the @Value annotation, as shown in the CustomerDetailsDTO snippet above.

The entity backing the projection is available in the target variable.

In the above example the field customerName is constructed by combining the First Name and Last Name fetched by the query execution.

Now we build the OrderDTO and utility to showcase how we can build nested projections.

In the classCustomerDetailsDTO, notice how we implement the custom logic to create the OrderDTO using a Spring bean utility class MapperUtility.

@Value("#{@mapperUtility.

buildOrderDTO(target.

orderNumber, target.

totalAmount)}")The SpEL expression refers to the bean MapperUtility which invokes the buildOrderDTO(.

,.

) method and forwards the projection orderNumber and totalAmount as a method parameters.

The custom method then returns an instance of OrderDTO making it a nested object in the CustomerDetailsDTO.

The RepositoryLet’s define standard Spring Data JPA repositories for the Customer model.

The class CustomerRepository, defines a method getCustomerDetails() to execute the named query ‘customerEntity.

getCustomerDetails’ defined in the orm.

xml.

Notice the return type of the method a list of projected DTO’s.

The Service LayerThe service layer now merely calls the repository instance and returns the projected DTO.

The API LayerFinally the API layer that helps triggering the underlying code, invokes the service method and returns the projected DTO to the caller.

The ResultWhen invoked the REST endpoint returns the DTO object, along with the nested ‘order’ field.

Final ThoughtsSpring Data REST projections can be used to create custom views of our models.

This help us reduce boiler plate code and makes the code more readable.

Again You can refer the sample project here.

.

. More details

Leave a Reply