@JoinColumn Annotation Explained – @JoinColumn注解的解释

最后修改: 2018年 9月 1日

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

1. Overview

1.概述

The annotation javax.persistence.JoinColumn marks a column as a join column for an entity association or an element collection.

注解javax.persistence.JoinColumn标记一个列作为实体关联或元素集合的连接列。

In this quick tutorial, we’ll show some examples of basic @JoinColumn usage.

在这个快速教程中,我们将展示一些基本的@JoinColumn使用实例。

2. @OneToOne Mapping Example

2.@OneToOne映射实例

The @JoinColumn annotation combined with a @OneToOne mapping indicates that a given column in the owner entity refers to a primary key in the reference entity:

@JoinColumn注解与@OneToOne映射相结合,表明所有者实体中的特定列是指参考实体中的主键。

@Entity
public class Office {
    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "addressId")
    private Address address;
}

The above code example will create a foreign key linking the Office entity with the primary key from the Address entity. The name of the foreign key column in the Office entity is specified by name property.

上面的代码示例将创建一个外键,将Office实体与Address实体的主键联系起来。Office实体中的外键列的名称由name属性指定。

3. @OneToMany Mapping Example

3.@OneToMany映射实例

When using a @OneToMany mapping, we can use the mappedBy parameter to indicate that the given column is owned by another entity:

当使用@OneToMany映射时,我们可以使用mappedBy参数来指示给定的列是由另一个实体拥有的。

@Entity
public class Employee {
 
    @Id
    private Long id;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "employee")
    private List<Email> emails;
}

@Entity
public class Email {
 
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "employee_id")
    private Employee employee;
}

In the above example, Email (the owner entity) has a join column employee_id that stores the id value and has a foreign key to the Employee entity.

在上面的例子中,Email(所有者实体)有一个连接列employee_id,它存储了id值,并且对Employee实体有一个外键。

joincol1

4. @JoinColumns

4.@JoinColumns

In situations when we want to create multiple join columns, we can use the @JoinColumns annotation:

在我们想创建多个连接列的情况下,我们可以使用@JoinColumns注解。

@Entity
public class Office {
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumns({
        @JoinColumn(name="ADDR_ID", referencedColumnName="ID"),
        @JoinColumn(name="ADDR_ZIP", referencedColumnName="ZIP")
    })
    private Address address;
}

The above example will create two foreign keys pointing to ID and ZIP columns in the Address entity:

上面的例子将创建两个外键,指向IDZIP实体中的Address列。

joincol2

5. Conclusion

5.结论

In this article, we learned how to use the @JoinColumn annotation. We looked at how to create both a single entity association and an element collection.

在这篇文章中,我们学习了如何使用@JoinColumn注解。我们研究了如何创建一个单一的实体关联和一个元素集合。

As always, all source code is available over on GitHub.

一如既往,所有的源代码都可以在GitHub上找到