session.getCurrentSession().createCriteria(MyClass.class) 弃用了现在如何使用 .addOrder()

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

我一直在开发:

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

其中:

@Autowired
SessionFactory session;

关于 createCriteria() 的替代方案,我创建了一个获取列表的方法:

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

但是我还是不知道用在什么地方:

addOrder(Order.asc("department_type_name"))

您需要使用 CriteriaQuery.orderBy() 来提供 order by 子句。

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();
}