@JoinColumn 和@MappedBy 是如何工作的

How @JoinColumn and @MappedBy works

我对@JoinColumn 和@MappedBy 的工作感到困惑。

考虑以下示例 这是我的部门 class 具有单向关系

@Entity
@Table(name = "DEPARTMENT")
public class Department {
    @Id
    @Column(name = "DEPARTMENT_ID")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer departmentId;
    @Column(name = "DEPARTMENT_NAME")
    private String departmentName;
    @Column(name = "LOCATION")
    private String location;

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JoinColumn(name = "DEPARTMENT_ID")
    private List<Employee> employees = new ArrayList<>();
}

我在 Department class 中有一个 list of employees,我在上面指定了 @JoinColumn,因此它将在 employee table 中添加 department_id FK。

但对于双向关系,我将定义 class 类似

Department.java
@Entity
@Table(name = "DEPARTMENT")
public class Department {
    @Id
    @Column(name = "DEPARTMENT_ID")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer departmentId;
    @Column(name = "DEPARTMENT_NAME")
    private String departmentName;
    @Column(name = "LOCATION")
    private String location;

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "department")
    private List<Employee> employees = new ArrayList<>();
}

Employee.java
@Entity
@Table(name = "EMPLOYEE")
public class Employee {
    @Id
    @SequenceGenerator(name = "emp_seq", sequenceName = "seq_employee")
    @GeneratedValue(generator = "emp_seq")
    @Column(name = "EMPLOYEE_ID")
    private Integer employeeId;
    @Column(name = "EMPLOYEE_NAME")
    private String employeeName;

    @ManyToOne
    @JoinColumn(name = "DEPARTMENT_ID")
    private Department department;
}

但是有双向关系,为什么我需要在 Employee class 中将 @JoinColumn 放在 department 上,并在 [=13] 中将 @MappedBy 放在 list of employees 上=]?

更新

那么@MappedBy 和@JoinColumn 是如何工作的?

实际上,您似乎没有使用 @MappedBy 注释,而是在 @OneToMany 中使用了 mappedBy = "department"

简单来说,mappedBy 告诉 hibernate 关系键在另一个 table 上(在本例中为 class)。

想一想:通常当您在任何数据库系统中 link 2 table 时,其中只有 1 个具有对另一个的外键约束,对吗?

什么MappedBy允许你link从不包含约束的table到另一个table.

关于@JoinColumn更简单,这里你有table外键,所以你告诉hibernate这不仅是一个列,而且是一个必须join[=的列37=]一个table.

The join column is declared with the @JoinColumn annotation which looks like the @Column annotation. It has one more parameters named referencedColumnName. This parameter declares the column in the targeted entity that will be used to the join. Note that when using referencedColumnName to a non primary key column, the associated class has to be Serializable. Also note that the referencedColumnName to a non primary key column has to be mapped to a property having a single column (other cases might not work).

查找 HERE hibernate 映射文档。