JPQL Create new Object In Select Statement - avoid or embrace?

JavaHibernateOrmJpaJpql

Java Problem Overview


I've learnt recently that it is possible to create new Objects in JPQL statements as follows:

select new Family(mother, mate, offspr)
from DomesticCat as mother
    join mother.mate as mate
    left join mother.kittens as offspr

Is this something to be avoided or rather to embrace? When is usage of this feature justified in the light of good practices?

Java Solutions


Solution 1 - Java

Don't avoid it, the SELECT NEW is there because there are perfectly valid use cases for it as reminded in the §10.2.7.2. JPQL Constructor Expressions in the SELECT Clause of the EJB 3.0 JPA Specification:

> A constructor may be used in the > SELECT list to return one or more Java > instances. The specified class is not > required to be an entity or to be > mapped to the database. The > constructor name must be fully > qualified. > > If an entity class name is specified > in the SELECT NEW clause, the > resulting entity instances are in the > new state. > > SELECT NEW com.acme.example.CustomerDetails(c.id, c.status, o.count) > FROM Customer c JOIN c.orders o > WHERE o.count > 100

In short, use the SELECT NEW when you don't want to retrieve a full entity or a full graph of objects in a type safe way (as opposed to an Object[]). Whether you map the result of a query in an entity class or a non mapped class will depend on your select. A typical example would be a list screen (where you might not want all the details).

In other words, don't use it everywhere but don't forbid its use (few things are only black or white).

Solution 2 - Java

You often use this sort of query when you want to retrieve a Data Transfer Object. Maybe a report can be a good place to use it. If you just want to retrieve a single domain object (like from Family instead), so there is no reason to use it.

Solution 3 - Java

An Object created with new does not have to be a DTO, i.e. an Object which will be exported by the Business layer. It can also be a POJO Domain Object, i.e. an Object used internally by the Business layer.

The reason to use this kind of POJOs as a partial Object instead of the full JPA Entity is performance in specific kinds of JOINS. A great resource which explains this is: http://use-the-index-luke.com/sql/join/hash-join-partial-objects

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmgamerView Question on Stackoverflow
Solution 1 - JavaPascal ThiventView Answer on Stackoverflow
Solution 2 - JavaArthur RonaldView Answer on Stackoverflow
Solution 3 - JavagmournosView Answer on Stackoverflow