我对使用@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<>();
}
我在list of employees中有一个Department class,在上面已指定@JoinColumn,因此它将在department_id中添加employee table FK。
但是,通过双向关系,我将定义类似的类
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;
}
但是,由于存在双向关系,为什么我需要将@JoinColumn放在departmentEmployee class之上,并在MappedBylist of employees的上方写@ Department class
更新
那么@MappedBy和@JoinColumn如何工作?

最佳答案

实际上,看来您不是在使用@MappedBy批注,而是在mappedBy = "department"中使用了@OneToMany

用简单的话来说,mappedBy告诉hibernate关系的键在另一个表上(在这种情况下是类)。

考虑一下:通常,当您在任何数据库系统中链接2个表时,其中只有1个表具有对另一个表的外键约束?

什么MappedBy允许您从不包含约束的表链接到另一个表。

关于@JoinColumn更加容易,这里您具有表外键,因此您告诉 hibernate 的这不仅是一列,而且还必须是联接表的列。



查找HERE hibernate映射文档。

10-07 18:22