views:

338

answers:

2

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?

+1  A: 

Hi,

You often use this sort of query when you want to retrieve a Data Tranfer 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.

Arthur Ronald F D Garcia
+1 for mentioning DTOs - exactly my use case
Simon Gibbs
+2  A: 

Don't avoid it, the SELECT NEW is there because there are perfectly valid use cases for it as reminded in the §4.8.2 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).

Pascal Thivent