JPA Join Types – JPA连接类型

最后修改: 2019年 4月 14日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this tutorial, we’ll look at different join types supported by JPA.

在本教程中,我们将了解JPA所支持的不同连接类型。

For this purpose, we’ll use JPQL, a query language for JPA.

为此,我们将使用JPQL,一种用于JPA的查询语言

2. Sample Data Model

2.数据模型样本

Let’s look at our sample data model that we’ll use in the examples.

让我们来看看我们将在例子中使用的样本数据模型。

First, we’ll create an Employee entity:

首先,我们将创建一个Employee实体。

@Entity
public class Employee {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    private String name;

    private int age;

    @ManyToOne
    private Department department;

    @OneToMany(mappedBy = "employee")
    private List<Phone> phones;

    // getters and setters...
}

Each Employee will be assigned to only one Department:

每个雇员将只被分配到一个部门

@Entity
public class Department {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    private String name;

    @OneToMany(mappedBy = "department")
    private List<Employee> employees;

    // getters and setters...
}

Finally, each Employee will have multiple Phones:

最后,每个雇员将有多个电话

@Entity
public class Phone {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    private String number;

    @ManyToOne
    private Employee employee;

    // getters and setters...
}

3. Inner Joins

3.内部连接

We’ll start with inner joins. When two or more entities are inner-joined, only the records that match the join condition are collected in the result.

我们将从内联开始。当两个或多个实体被内连接时,只有符合连接条件的记录才会被收集到结果中。

3.1. Implicit Inner Join With Single-Valued Association Navigation

3.1.隐式内联与单值关联导航

Inner joins can be implicit. As the name implies, the developer doesn’t specify implicit inner joins. Whenever we navigate a single-valued association, JPA automatically creates an implicit join:

内部连接可以是隐式的。顾名思义,开发者不指定隐式内部连接。每当我们浏览一个单值关联时,JPA会自动创建一个隐式连接。

@Test
public void whenPathExpressionIsUsedForSingleValuedAssociation_thenCreatesImplicitInnerJoin() {
    TypedQuery<Department> query
      = entityManager.createQuery(
          "SELECT e.department FROM Employee e", Department.class);
    List<Department> resultList = query.getResultList();
    
    // Assertions...
}

Here, the Employee entity has a many-to-one relationship with the Department entity. If we navigate from an Employee entity to her Department, specifying e.department, we’ll be navigating a single-valued association. As a result, JPA will create an inner join. Furthermore, the join condition will be derived from mapping metadata.

在这里,Employee实体与Department实体有多对一的关系。如果我们从Employee实体导航到她的Department,指定e.department,我们将导航一个单值的关联。因此,JPA将创建一个内部连接。此外,连接条件将从映射元数据中导出。

3.2. Explicit Inner Join With Single-Valued Association

3.2.带有单值关联的显式内联

Next we’ll look at explicit inner joins where we use the JOIN keyword in our JPQL query:

接下来我们来看看显式内联,其中我们在JPQL查询中使用JOIN关键字

@Test
public void whenJoinKeywordIsUsed_thenCreatesExplicitInnerJoin() {
    TypedQuery<Department> query
      = entityManager.createQuery(
          "SELECT d FROM Employee e JOIN e.department d", Department.class);
    List<Department> resultList = query.getResultList();
    
    // Assertions...
}

In this query, we specified a JOIN keyword and the associated Department entity in the FROM clause, whereas in the previous query they weren’t specified at all. However, other than this syntactic difference, the resulting SQL queries will be very similar.

在这个查询中,我们在FROM子句中指定了一个JOIN关键字和相关的Department实体,而在前面的查询中根本没有指定它们。然而,除了这个语法上的差异外,所产生的SQL查询将非常相似。

We can also specify an optional INNER keyword:

我们还可以指定一个可选的INNER关键字。

@Test
public void whenInnerJoinKeywordIsUsed_thenCreatesExplicitInnerJoin() {
    TypedQuery<Department> query
      = entityManager.createQuery(
          "SELECT d FROM Employee e INNER JOIN e.department d", Department.class);
    List<Department> resultList = query.getResultList();

    // Assertions...
}

So since JPA automatically creates an implicit inner join, when would we need to be explicit?

那么,既然JPA自动创建了一个隐式内联,我们什么时候才需要显式呢?

First of all, JPA only creates an implicit inner join when we specify a path expression. For example, when we want to select only the Employees that have a Department, and we don’t use a path expression like e.department, we should use the JOIN keyword in our query.

首先,JPA只在我们指定一个路径表达式时创建一个隐式内联。例如,当我们想只选择有部门的雇员时,而我们没有使用e.department这样的路径表达式,我们应该在查询中使用JOIN关键字。

Second, when we’re explicit, it can be easier to know what is going on.

第二,当我们明确时,可以更容易知道发生了什么。

3.3. Explicit Inner Join With Collection-Valued Associations

3.3.带有集合值关联的显式内联

Another place we need to be explicit is with collection-valued associations.

另一个地方我们需要明确的是集合值关联。

If we look at our data model, the Employee has a one-to-many relationship with Phone. As in an earlier example, we can try to write a similar query:

如果我们看一下我们的数据模型,EmployeePhone有一个一对多的关系。正如前面的例子,我们可以尝试写一个类似的查询。

SELECT e.phones FROM Employee e

However, this won’t quite work as we may have intended. Since the selected association, e.phones, is collection-valued, we’ll get a list of Collections instead of Phone entities:

然而,这并不能完全按照我们的意图工作。因为选择的关联,e. phones,是集合值,我们将得到一个Collections的列表,而不是Phoneentities

@Test
public void whenCollectionValuedAssociationIsSpecifiedInSelect_ThenReturnsCollections() {
    TypedQuery<Collection> query 
      = entityManager.createQuery(
          "SELECT e.phones FROM Employee e", Collection.class);
    List<Collection> resultList = query.getResultList();

    //Assertions
}

Moreover, if we want to filter Phone entities in the WHERE clause, JPA won’t allow that. This is because a path expression can’t continue from a collection-valued association. So for example, e.phones.number isn’t valid.

此外,如果我们想在WHERE子句中过滤Phone实体,JPA将不允许这样做。这是因为路径表达式不能从一个集合值关联中继续下去。因此,例如,e. phones.number是无效的

Instead, we should create an explicit inner join and create an alias for the Phone entity. Then we can specify the Phone entity in the SELECT or WHERE clause:

相反,我们应该创建一个显式内联,并为Phone实体创建一个别名。然后我们可以在SELECT或WHERE子句中指定Phone实体。

@Test
public void whenCollectionValuedAssociationIsJoined_ThenCanSelect() {
    TypedQuery<Phone> query 
      = entityManager.createQuery(
          "SELECT ph FROM Employee e JOIN e.phones ph WHERE ph LIKE '1%'", Phone.class);
    List<Phone> resultList = query.getResultList();
    
    // Assertions...
}

4. Outer Join

4.外层连接

When two or more entities are outer-joined, the records that satisfy the join condition, as well as the records in the left entity, are collected in the result:

当两个或多个实体被外接时,满足连接条件的记录以及左边实体中的记录被收集到结果中:

@Test
public void whenLeftKeywordIsSpecified_thenCreatesOuterJoinAndIncludesNonMatched() {
    TypedQuery<Department> query 
      = entityManager.createQuery(
          "SELECT DISTINCT d FROM Department d LEFT JOIN d.employees e", Department.class);
    List<Department> resultList = query.getResultList();

    // Assertions...
}

Here, the result will contain Departments that have associated Employees and also the ones that don’t have any.

这里,结果将包含有关联的部门和没有关联的雇员

This is also referred to as a left outer join. JPA doesn’t provide right joins where we also collect non-matching records from the right entity. Although, we can simulate right joins by swapping entities in the FROM clause.

这也被称为左外连接。JPA不提供右连接,在这种情况下,我们也会从右边的实体收集不匹配的记录。虽然,我们可以通过在FROM子句中交换实体来模拟右连接。

5. Joins in the WHERE Clause

5.WHERE子句中的连接

5.1. With a Condition

5.1.有一个条件

We can list two entities in the FROM clause and then specify the join condition in the WHERE clause.

我们可以在FROM子句中列出两个实体, 然后在WHERE子句中指定连接条件

This can be handy, especially when database level foreign keys aren’t in place:

这可能很方便,特别是当数据库级别的外键没有到位的时候。

@Test
public void whenEntitiesAreListedInFromAndMatchedInWhere_ThenCreatesJoin() {
    TypedQuery<Department> query 
      = entityManager.createQuery(
          "SELECT d FROM Employee e, Department d WHERE e.department = d", Department.class);
    List<Department> resultList = query.getResultList();
    
    // Assertions...
}

Here, we’re joining Employee and Department entities, but this time specifying a condition in the WHERE clause.

在这里,我们正在连接EmployeeDepartment实体,但这次在WHERE子句中指定了一个条件。

5.2. Without a Condition (Cartesian Product)

5.2.无条件(笛卡尔乘积)

Similarly, we can list two entities in the FROM clause without specifying any join condition. In this case, we’ll get a cartesian product back. This means that every record in the first entity is paired with every other record in the second entity:

同样地,我们可以在FROM子句中列出两个实体,而不指定任何连接条件。在这种情况下,我们会得到一个笛卡尔乘积。这意味着第一个实体中的每条记录都与第二个实体中的其他每条记录成对。

@Test
public void whenEntitiesAreListedInFrom_ThenCreatesCartesianProduct() {
    TypedQuery<Department> query
      = entityManager.createQuery(
          "SELECT d FROM Employee e, Department d", Department.class);
    List<Department> resultList = query.getResultList();
    
    // Assertions...
}

As we can guess, these kinds of queries won’t perform well.

正如我们可以猜到的,这类查询不会有好的表现。

6. Multiple Joins

6.多重连接

So far, we’ve used two entities to perform joins, but this isn’t a rule. We can also join multiple entities in a single JPQL query:

到目前为止,我们已经使用两个实体来执行连接,但这并不是一个规则。我们也可以在一个JPQL查询中连接多个实体

@Test
public void whenMultipleEntitiesAreListedWithJoin_ThenCreatesMultipleJoins() {
    TypedQuery<Phone> query
      = entityManager.createQuery(
          "SELECT ph FROM Employee e
      JOIN e.department d
      JOIN e.phones ph
      WHERE d.name IS NOT NULL", Phone.class);
    List<Phone> resultList = query.getResultList();
    
    // Assertions...
}

Here we’re selecting all Phones of all Employees that have a Department. Similar to other inner joins, we’re not specifying conditions since JPA extracts this information from mapping metadata.

在这里,我们要选择所有有部门的员工的所有手机与其他内部连接类似,我们没有指定条件,因为JPA从映射元数据中提取这一信息。

7. Fetch Joins

7.获取连接

Now let’s talk about fetch joins. Their primary usage is for fetching lazy-loaded associations eagerly for the current query.

现在让我们来谈一谈fetch joins。它们的主要用途是为当前查询急切地获取懒散加载的关联

Here we’ll eagerly load Employees association:

这里我们将急切地加载Employees的关联。

@Test
public void whenFetchKeywordIsSpecified_ThenCreatesFetchJoin() {
    TypedQuery<Department> query 
      = entityManager.createQuery(
          "SELECT d FROM Department d JOIN FETCH d.employees", Department.class);
    List<Department> resultList = query.getResultList();
    
    // Assertions...
}

Although this query looks very similar to other queries, there is one difference; the Employees are eagerly loaded. This means that once we call getResultList in the test above, the Department entities will have their employees field loaded, thus saving us another trip to the database.

虽然这个查询看起来与其他查询非常相似,但有一点不同;Employees被急切地加载。这意味着一旦我们在上面的测试中调用getResultListDepartment实体将加载其employees字段,从而节省了我们去数据库的另一趟旅程。

However, we must be aware of the memory trade-off. We may be more efficient because we only performed one query, but we also loaded all Departments and their employees into memory at once.

然而,我们必须意识到内存的折衷。我们可能会更有效率,因为我们只进行了一次查询,但是我们也将所有的Departments和他们的雇员一次性加载到内存中。

We can also perform the outer fetch join in a similar way to outer joins, where we collect records from the left entity that don’t match the join condition. In addition, it eagerly loads the specified association:

我们也可以用类似于外层连接的方式来执行外层获取连接,我们从左侧实体中收集不符合连接条件的记录。此外,它还急切地加载指定的关联。

@Test
public void whenLeftAndFetchKeywordsAreSpecified_ThenCreatesOuterFetchJoin() {
    TypedQuery<Department> query 
      = entityManager.createQuery(
          "SELECT d FROM Department d LEFT JOIN FETCH d.employees", Department.class);
    List<Department> resultList = query.getResultList();
    
    // Assertions...
}

8. Summary

8.摘要

In this article, we covered JPA join types.

在这篇文章中,我们介绍了JPA连接类型。

As always, the samples for this and other tutorials are available over on GitHub.

像往常一样,本教程和其他教程的样本可在GitHub上获得over