session.getCurrentSession()。createCriteria(MyClass.class)不建议立即使用.addOrder()

时间:2019-02-10 09:57:39

标签: java hibernate sql-order-by deprecated createcriteria

我一直在与:

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

位置:

@Autowired
SessionFactory session;

this QuestioncreateCriteria()的替代方法,我创建了一种获取列表的方法:

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"))

1 个答案:

答案 0 :(得分:1)

您需要使用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();
}