本文為【Spring Boot情境式網站開發指南:使用Spring Data JPA、Spring Security、Spring Web Flow】一書的【 第4章 Criteria API入門】延續,完整範例程式碼可至出版社下載
Criteria API使用CriteriaBuilder的方法asc()做升冪(ascending)排序,使用方法desc()表示降冪(descending)排序。
使用asc()、desc()排序
以下範例行8使用CriteriaBuilder的方法asc()傳入salary欄位以建立升冪Order物件,行9則使用desc()建立降冪Order物件,可擇一使用;最終傳入CriteriaQuery的orderBy()方法中:
@Test
public void Criteria_OrderByAsc() {
EntityManager em = emf.createEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery sql = cb.createQuery(Employee.class);
Root emp = sql.from(Employee.class);
sql.select(emp);
Order salaryOrder = cb.asc(emp.get(Employee_.salary));
// Order salaryOrder = cb.desc(emp.get(Employee_.salary));
sql.orderBy(salaryOrder);
TypedQuery typedQuery = em.createQuery(sql);
List resultList = typedQuery.getResultList();
resultList.forEach(System.out::println);
em.close();
assertThat(resultList, contains(employee3, employee1, employee2));
}
前述範例等價於使用以下JPQL查詢:
SELECT e FROM Employee e ORDER BY e.salary
// SELECT e FROM Employee e ORDER BY e.salary ASC
多欄位排序
CriteriaQuery的orderBy()方法中可以接受多個Order物件,並使用不同的asc()或desc(),如以下範例程式行8、9,以完成多欄位排序:
@Test
public void Criteria_OrderByMultiColumns() {
EntityManager em = emf.createEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery sql = cb.createQuery(Employee.class);
Root emp = sql.from(Employee.class);
sql.select(emp)
.orderBy( cb.asc(emp.get(Employee_.dept)),
cb.desc(emp.get(Employee_.salary)) );
TypedQuery typedQuery = em.createQuery(sql);
List resultList = typedQuery.getResultList();
resultList.forEach(System.out::println);
em.close();
assertThat(resultList, contains(employee2, employee1, employee3));
}
前述範例等價於使用以下JPQL查詢:
SELECT e FROM Employee e ORDER BY e. dept ASC, e.salary DESC
沒有留言:
張貼留言