JPA 2.0: loading a subset of fields for an object

I have an Entity named address. Entity address has several fields, one of which is CITY. I created a query by calling entityManager.createQuery, but my query only includes the CITY field in the select clause (because I only want to load this field). The CITY field is of type String. When I get my list of results, I do not get a list of Address objects, but instead a list of Object [].

Is there a way to create an address list instead of an Object [] list? My JPA provider is sleep mode, latest version. I want a solution that does not require the use of any Hibernate specific.

+7
source share
2 answers

This is possible with a constructor expression in your request. Normally you would use this with a custom DTO, but it should work with an entity. First, create an additional constructor in your object that accepts only the necessary fields:

public Address() { //default constructor } public Address(String city) { this.city = city; } 

Then your query might look like this:

 select new your.package.Address(a.city) from Address a where ... 

Please note that the resulting object is not bound to the EntityManager, therefore changes to it will not be saved automatically.

+14
source

How would Hibernate load address instances if you request cities? JPA entities are objects, and objects must perceive invariants. For example, one of such invariants may be that the address always has an identifier, street, etc. If Hibernate loads partial objects (only with a filled city attribute), these invariants will be broken and you will no longer be able to rely on your own code. You would also have all kinds of problems if you tried to attach such an address to another object or just tried to delete because it didn’t even have an identifier.

So, the short answer is no: it is not possible.

The long answer is that since the Address is a POJO, you just need to create Addresses from busy cities on your own or using ResultTransformer. But you will get temporary address addresses, not attached Address objects. This is a recipe for countless errors and confusion, IMHO.

+2
source

All Articles