2020年7月19日 星期日

LEFT OUTER JOIN

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

使用LEFT OUTER JOIN並擷取Employee所有欄位

當JPQL使用以下語句時:
SELECT DISTINCT e FROM Employee e 
       LEFT OUTER JOIN e.tasks t
對應的Criteria API用法如下:
@Test
public void Criteria_LeftJoin1() {
    EntityManager em = emf.createEntityManager();
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery sql = cb.createQuery(Employee.class);
    Root emp = sql.from(Employee.class);
    emp.join(Employee_.tasks, JoinType.LEFT);
    sql.select(emp)
        .distinct(true);
    TypedQuery typedQuery = em.createQuery(sql);
    List resultList = typedQuery.getResultList();
    resultList.forEach(System.out::println);
    assertThat(resultList, containsInAnyOrder(
            employee1, employee2, 
            employee3, employee4));
    assertThat(resultList, hasSize(4));
}
說明:
  • 行7:
emp.join(Employee_.tasks, JoinType.LEFT);等價於Employee e LEFT OUTER JOIN e.tasks t。方法join()未指定JoinType時預設為JoinType.INNER。本例為LEFT JOIN,需指定JoinType.LEFT。

使用LEFT OUTER JOIN擷取Employee的name與Task的description欄位

承前例,但查詢的欄位改為「e.name, t.name」。當JPQL使用以下語句時:
SELECT DISTINCT e.name, t.name 
    FROM Employee e 
     LEFT OUTER JOIN e.tasks t
對應的Criteria API用法如下:
@Test 
public void Criteria_LeftJoin2() {
    EntityManager em = emf.createEntityManager();
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery sql = cb.createTupleQuery();
    Root emp = sql.from(Employee.class);
    Join task = emp.join(Employee_.tasks, JoinType.LEFT);
    // task.on(cb.equal(task.get(Task_.name), "Denise"));
    sql.select(cb.tuple(emp.get(Employee_.name).alias("employeeName"),
                         task.get(Task_.name).alias("supervisor")))
        .distinct(true);
    TypedQuery typedQuery = em.createQuery(sql);
    List resultList = typedQuery.getResultList();
    List rows = resultList.stream()
            .map(t -> t.get("employeeName", String.class) + ", " + 
                        t.get("supervisor", String.class))
            .collect(Collectors.toList());
    rows.forEach(System.out::println);
    em.close();
    assertThat(rows, containsInAnyOrder(
            "Tim, Mike", 
            "Tim, Denise",
            "Mike, Rose",
            "Mike, Mike",
            "Jim, Denise", 
            "Jack, null"));
    assertThat(rows, hasSize(6));
    /*      
    assertThat(rows, containsInAnyOrder(
            "Jim, Denise", 
            "Jack, null", 
            "Mike, null",
            "Tim, Denise"));
    assertThat(rows, hasSize(4));
    */  
}
說明:

  • 行7:
因為必須查詢聯結表格Task的欄位,因此建立Join<Employee, Task> task的物件參考指向join()方法執行結果。
  • 行8:
可以藉由Join<Employee, Task> task的on()方法限定對聯結表格Task的查詢條件,對應的JPQL子句為「LEFT OUTER JOIN e.tasks t ON t.name='Denise'」。本行若取消comment,將改得到行29-34的結果;或改執行單元測試方方法Criteria_LeftJoinOn()驗證結果。
  • 行10:
指定要查詢Task的name欄位。

沒有留言:

張貼留言