Creating slim Database Projections using JPA2 Constructor Expressions
Sunday, April 14th, 2013One common question that you may encounter one day when using object-relational-mapping in your application is how to slim down data that you’re retrieving from the persistence layer down to a specific subset for your use-case in an efficient manner and without using complex additional mapping frameworks. In some situations you might declare lazy loaded fields but another approach that I’d like to share with you here are JPA2 constructor expressions.
Constructor expressions allow us to create plain old java objects from the result of an JPA query. The advantage is that we may use different projections for different scenarios and without being managed, the POJOs might help us save some resources here.
In the following tutorial, we’re going to persist 100 book entities with multiple properties to an embedded database and we’re using constructor expressions afterwards to create smaller POJOs using a subset of the information available from each persisted book.