本文為【Spring Boot情境式網站開發指南:使用Spring Data JPA、Spring Security、Spring Web Flow】一書的【 第4章 Criteria API入門】延續,完整範例程式碼可至出版社下載
使用 IS NULL 查詢
當JPQL使用以下查詢時:SELECT e FROM Employee e WHERE e.dept IS NULL對應的Criteria API用法如下:
@Test
public void Criteria_IsNull() {
EntityManager em = emf.createEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery sql = cb.createQuery(Employee.class);
Root emp = sql.from(Employee.class);
sql.select(emp)
.where(emp.get(Employee_.dept).isNull());
// .where(cb.equal(emp.get(Employee_.dept), cb.nullLiteral(String.class)));
TypedQuery typedQuery = em.createQuery(sql);
List resultList = typedQuery.getResultList();
resultList.forEach(System.out::println);
em.close();
assertThat(resultList, containsInAnyOrder(employee4));
assertThat(resultList, hasSize(1));
}
行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使用以下查詢時:SELECT e FROM Employee e WHERE e.dept IS NOT NULL
對應的Criteria API用法如以下範例行8的isNotNull():@Test
public void Criteria_IsNotNull() {
EntityManager em = emf.createEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery sql = cb.createQuery(Employee.class);
Root emp = sql.from(Employee.class);
sql.select(emp)
.where(emp.get(Employee_.dept).isNotNull());
TypedQuery typedQuery = em.createQuery(sql);
List resultList = typedQuery.getResultList();
resultList.forEach(System.out::println);
em.close();
assertThat(resultList, containsInAnyOrder(employee1, employee2, employee3));
assertThat(resultList, hasSize(3));
}
沒有留言:
張貼留言