2020年7月19日 星期日

在WHERE敘述使用比較(Comparision)關鍵字:NULL


本文為【Spring Boot情境式網站開發指南:使用Spring Data JPA、Spring Security、Spring Web Flow】一書的【 第4章 Criteria API入門】延續,完整範例程式碼可至出版社下載

使用「isNull()」或「isNotNull()」可以查詢一般欄位物件值是否為null。

使用 IS NULL 查詢

當JPQL使用以下查詢時:
  1. SELECT e FROM Employee e WHERE e.dept IS NULL
對應的Criteria API用法如下:
  1. @Test
  2. public void Criteria_IsNull() {
  3. EntityManager em = emf.createEntityManager();
  4. CriteriaBuilder cb = em.getCriteriaBuilder();
  5. CriteriaQuery sql = cb.createQuery(Employee.class);
  6. Root emp = sql.from(Employee.class);
  7. sql.select(emp)
  8. .where(emp.get(Employee_.dept).isNull());
  9. // .where(cb.equal(emp.get(Employee_.dept), cb.nullLiteral(String.class)));
  10. TypedQuery typedQuery = em.createQuery(sql);
  11. List resultList = typedQuery.getResultList();
  12. resultList.forEach(System.out::println);
  13. em.close();
  14. assertThat(resultList, containsInAnyOrder(employee4));
  15. assertThat(resultList, hasSize(1));
  16. }
行8:
使用欄位表示式物件emp.get(Employee_.dept)的isNull()方法,等價於「e.dept IS NULL」
行9:
也可以使用CriteriaBuilder的equal()方法,第1個參數指定欄位dept,第2個參數則為CriteriaBuilder的nullLiteral(String.class)方法,等價於「e.dept = NULL」。

使用 IS NOT NULL 查詢

當JPQL使用以下查詢時:
  1. SELECT e FROM Employee e WHERE e.dept IS NOT NULL
對應的Criteria API用法如以下範例行8的isNotNull():
  1. @Test
  2. public void Criteria_IsNotNull() {
  3. EntityManager em = emf.createEntityManager();
  4. CriteriaBuilder cb = em.getCriteriaBuilder();
  5. CriteriaQuery sql = cb.createQuery(Employee.class);
  6. Root emp = sql.from(Employee.class);
  7. sql.select(emp)
  8. .where(emp.get(Employee_.dept).isNotNull());
  9. TypedQuery typedQuery = em.createQuery(sql);
  10. List resultList = typedQuery.getResultList();
  11. resultList.forEach(System.out::println);
  12. em.close();
  13. assertThat(resultList, containsInAnyOrder(employee1, employee2, employee3));
  14. assertThat(resultList, hasSize(3));
  15. }

沒有留言:

張貼留言