javahibernatesql-order-bydeprecatedcreatecriteria

session.getCurrentSession().createCriteria(MyClass.class) deprecated how to use .addOrder() now


I have been developing with:

public List<DepartmentType> getAllDepartmentTypes() {
    return session.getCurrentSession()
                .createCriteria(DepartmentType.class)
                .addOrder(Order.asc("department_type_name"))
                .list();
}

Where:

@Autowired
SessionFactory session;

From this Question about alternatives to createCriteria(), I have created a method to get lists:

public List<DepartmentType> getAllDepartmentTypes() {
    CriteriaBuilder builder = session.getCurrentSession().getCriteriaBuilder();
    CriteriaQuery<DepartmentType> criteriaQuery = builder.createQuery(DepartmentType.class);    
    return session.getCurrentSession()
                .createQuery(criteriaQuery)
                .getResultList();
}

But I still don't know where to use:

addOrder(Order.asc("department_type_name"))

Solution

  • You need to use CriteriaQuery.orderBy() to provide the order by clause.

    public List<DepartmentType> getAllDepartmentTypes() {
        CriteriaBuilder builder = session.getCurrentSession().getCriteriaBuilder();
        CriteriaQuery<DepartmentType> criteriaQuery = builder.createQuery(DepartmentType.class);    
        Root<DepartmentType> deptType = criteriaQuery.from(DepartmentType.class);
        criteriaQuery.select(deptType).orderBy(builder.asc(deptType.get("department_type_name")));
        return session.getCurrentSession()
                    .createQuery(criteriaQuery)
                    .getResultList();
    }