Search code examples
javahibernatehibernate-criteria

In Hibernate 5, what's the CriteriaQuery equivalent of Criteria's restriction and projection?


Before Hibernate 5 deprecated the Criteria class, you could add restrictions to a Criteria to act as a constraint, and projections to act as select statements, like so

Criteria criteria = session.createCriteria(T.class)
    .add(Restrictions.or(Restrictions.eq(property, constraintValue)
    .set(Projection(Projections.projectionList()
    .add(Projections.property(selectValue)));

But, since you now need to use CriteriaQuery like so,

 CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
 CriteriaQuery<T> criteriaQuery = criteriaBuilder.createQuery(T.class);
 Root<T> root = criteriaQuery.from(T.class);
 criteriaQuery.select(root);

 Query<T> query = session.createQuery(criteriaQuery);

However I have been unable to figure out how to add certain things which are required in SQL statements, mainly because searching for documentation tends to wind up on documentation about Criteria, due to the naming similarity.

So, how can I recreate a simple query, like the one below, using CriteriaQuery?

SELECT selectValue  
FROM tables.T  
WHERE property = constraintValue

Solution

  • Source.

    Has multiple examples, but turns out that the simple select statement we were trying to recreate can be done like so:

    CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
    CriteriaQuery<SELECTVALUETYPE> criteriaQuery = criteriaBuilder.createQuery(SELECTVALUETYPE.class);
    Root<PARENTCLASS> root = criteriaQuery.from(PARENTCLASS.class);
    criteriaQuery.select(root);
    criteriaQuery.where(criteriaBuilder.equal(root.get(property), constraintValue));
    
    Query<SELECTVALUETYPE> query = session.createQuery(criteriaQuery);
    

    Note that this is a generic answer, and won't actually run. The reason being, SELECTVALUETYPE needs to be replaced with the data type of selectValue.
    For example, CriteriaQuery might become:

    • String selectValue -> CriteriaQuery
    • T selectValue -> CriteriaQuery

    Therefore, a working example for the statement

    Select name  
    From Users  
    Where ID = 1
    

    Could be expressed with the following block

    int ID = 1;
    CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
    CriteriaQuery<String> criteriaQuery = criteriaBuilder.createQuery(String.class);
    Root<User> root = criteriaQuery.from(User.class);
    criteriaQuery.select(root.get("name");
    criteriaQuery.where(criteriaBuilder.equal(root.get("ID"), ID));
    
    Query<String> query = session.createQuery(criteriaQuery);
    
    List<String>results = query.getResultList();
    for(String name : results){
        System.out.println("Name: " + name);
    }