Search code examples
hibernatehibernate-criteriajpa-criteria

Alternate way for the code using JPA criteria


With deprecation of createCriteria() in Criteria class in Hibernate 5.2.2, many of its related functions can't be used anymore. I have found an alternative use for criteria.createAlias(String, String) and adding Restriction from the following link Deprecated createCriteria method in Hibernate 5 But I can't find how to substitute in JPA criteria the following functions available in Criteria:

    criteria.setProjection(Projections.projectionList()
                           .add(Projections.distinct(Projections.property("student.id")), "id")
                           .add(Projections.property("student.name"), "name"));
    criteria.addOrder(Order.asc("student.name"));
    if (limit != null)
        criteria.setMaxResults(limit);
    if (offset != null)
        criteria.setFirstResult(offset);
    criteria.setResultTransformer(new AliasToBeanResultTransformer(Student.class));

Please provide me an alternative way to write the same code using JPA criteria API.


Solution

  • So far I have found the following alternate way:

        CriteriaBuilder builder = sessionFactory.getCriteriaBuilder();
        CriteriaQuery<Student> criteriaQuery = builder.createQuery(Student.class);
        //Perform the required join
    criteriaQuery.multiselect(student.get("id").alias("id"),student.get("name").alias("name")).distinct(true);
        criteriaQuery.orderBy(builder.asc(student.get("name")));
        TypedQuery typedQuery = entityManager.createQuery(criteriaQuery);
        if (limit != null)
          typedQuery.setMaxResults(limit);
        if (offset != null)
          typedQuery.setFirstResult(offset);
        List<Student> resultList = typedQuery.getResultList();
    

    My problem was solved with the above solution. JPA criteria doesn't require AliasToBeanResultTransformer(). It transform itself to the required bean.