使用CriteriaBuilder的isEmpty()或isNotEmpty()方法可以查詢集合型態的物件欄位值是否為空(empty)。
使用 IS EMPTY 查詢
當JPQL使用以下查詢時:SELECT e FROM Employee1 e WHERE e.tasks IS EMPTY對應的Criteria API用法如下:
@Test
public void Criteria_JoinedEntityIsEmpty() {
EntityManager em = emf.createEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery sql = cb.createQuery(Employee1.class);
Root emp1 = sql.from(Employee1.class);
sql.select(emp1)
.where( cb.isEmpty(emp1.get(Employee1_.tasks)) );
List resultList = em.createQuery(sql).getResultList();
resultList.forEach(System.out::println);
em.close();
assertThat(resultList, containsInAnyOrder(employee4, employee2));
assertThat(resultList, hasSize(2));
}
行8:使用CriteriaBuilder的isEmpty()方法查詢集合型態的欄位Employee1_.tasks是否為空(empty)。
使用 IS NOT EMPTY 查詢
當JPQL使用以下查詢時:SELECT e FROM Employee1 e WHERE e.tasks IS NOT EMPTY
對應的Criteria API用法如下: @Test
public void Criteria_JoinedEntityIsNotEmpty() {
EntityManager em = emf.createEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery sql = cb.createQuery(Employee1.class);
Root emp1 = sql.from(Employee1.class);
sql.select(emp1)
.where( cb.isNotEmpty(emp1.get(Employee1_.tasks)) );
List resultList = em.createQuery(sql).getResultList();
resultList.forEach(System.out::println);
em.close();
assertThat(resultList, contains(employee1, employee3));
assertThat(resultList, hasSize(2));
}
行8:使用CriteriaBuilder的isNotEmpty()方法查詢集合型態的欄位Employee1_.tasks是否不為空(empty)。
對一般欄位使用 IS NULL 敘述
對非集合物件型態的一般欄位應該使用使用isNull()方法判斷是否為空(null)。當JPQL使用以下查詢時:SELECT DISTINCT e FROM Employee1 e INNER JOIN e.tasks t WHERE t.name IS NULL
對應的Criteria API用法如下:@Test
public void Criteria_JoinedEntityFieldIsEmpty() {
EntityManager em = emf.createEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery sql = cb.createQuery(Employee1.class);
Root emp1 = sql.from(Employee1.class);
ListJoin tasks = emp1.join(Employee1_.tasks);
sql.select(emp1)
.distinct(true)
.where(cb.isNull(tasks.get(Task_.name)));
List resultList = em.createQuery(sql).getResultList();
resultList.forEach(System.out::println);
em.close();
assertThat(resultList, contains(employee3));
assertThat(resultList, hasSize(1));
}
行10:使用CriteriaBuilder的isNull()方法查詢非集合型態的欄位Task_.name是否為空(null)。
沒有留言:
張貼留言