3.2. Special expressions

3.2.1. Constructor projections

Querydsl provides the possibility to use constructor invocations in projections. To use a constructor in a query projection, you need to annotate it with the QueryProjection annotation :

class CustomerDTO {

  @QueryProjection
  public CustomerDTO(long id, String name){
     ...
  }

}

And then you can use it like this in the query

QCustomer customer = QCustomer.customer;
HQLQuery query = new HibernateQuery(session);
List<CustomerDTO> dtos = qry.from(customer).list(new QCustomerDTO(customer.id, customer.name));     

While the example is Hibernate specific, this feature is present in all modules.

If the type with the QueryProjection annotation is not an annotated entity type, you can use the constructor projection like in the example, but if the annotated type would be an entity type, then the constructor projection would need to be created via a call to the static create method of the query type :

@Entity
class Customer {

  @QueryProjection
  public Customer(long id, String name){
     ...
  }

}
QCustomer customer = QCustomer.customer;
HQLQuery query = new HibernateQuery(session);
List<Customer> dtos = qry.from(customer).list(new QCustomer.create(customer.id, customer.name));   

3.2.2. Complex boolean expressions

To construct complex boolean expressions, use the BooleanBuilder class. It extends EBoolean and can be used in cascaded form :

public List<Customer> getCustomer(String... names){
    QCustomer customer = QCustomer.customer;    
    HibernateQuery qry = new HibernateQuery(session).from(customer);    
    BooleanBuilder builder = new BoolenBuilder();
    for (String name : names){
        builder.or(customer.name.eq(name));
    }
    qry.where(builder); // customer.name eq name1 OR customer.name eq name2 OR ...  
    return qry.list(customer);
}

3.2.3. Case expressions

To construct case-when-then-else expressions use the CaseBuilder class like this :

    
QCustomer customer = QCustomer.customer;    
Expr<String> cases = new CaseBuilder()
    .when(customer.annualSpending.gt(10000)).then("Premier")
    .when(customer.annualSpending.gt(5000)).then("Gold")
    .when(customer.annualSpending.gt(2000)).then("Silver")
    .otherwise("Bronze");
// The cases expression can now be used in a projection or condition        

For case expressions with equals-operations use the following simpler form instead :

    
QCustomer customer = QCustomer.customer;    
Expr<String> cases = customer.annualSpending
    .when(10000).then("Premier")
    .when(5000).then("Gold")
    .when(2000).then("Silver")
    .otherwise("Bronze");
// The cases expression can now be used in a projection or condition        

Case expressions are not yet supported in JDOQL.