Loading...

Constructor expressions in JPQL

:heavy_exclamation_mark: This post is older than a year. Consider some information might not be accurate anymore. :heavy_exclamation_mark:

In JPA it is possible to create directly a new object from JPQL SELECT statement, instead of fetching the result list and mapping the attributes. The JPA supports the constructor expressions for that.

A constructor may be used in the SELECT list to return an instance of a Java class. The specified class is not required to be an entity or to be mapped to the database. The constructor name must be fully qualified.

4.8.2 Constructor Expressions in the SELECT Clause, JSR-317 - Java Persistence 2.0, Page 162 A simple DTO (Data Transfer Object, POJO):

public class CustomerDetails {
    private long id;
    private String name;
    public CustomerDetails(long id, String description) {
        this.id = id;
        this.name = description;
    }
//..
}

The repository implementation:

@Override
public CustomerDetails getCustomerDetails(Long customerId) {
    StringBuilder sb = new StringBuilder();
    sb.append("SELECT NEW net.cinhtau.demo.dto.CustomerDetails(c.id, c.name) ");
    sb.append("FROM Customer c ");
    sb.append("WHERE c.id = :id ");
    TypedQuery<CustomerDetails> query = em.createQuery(sb.toString(), CustomerDetails.class);
    query.setParameter("id", customerId);
    return query.getSingleResult();
}

Pay attention that desired object has to be fully qualified (see above).

jpa
Please remember the terms for blog comments.