编程语言
首页 > 编程语言> > java – @JoinColumn和@MappedBy如何工作

java – @JoinColumn和@MappedBy如何工作

作者:互联网

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

考虑以下示例
这是我的Department类,具有单向关系

@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类的员工列表,我已经指定了@JoinColumn,因此它会在employee表中添加department_id 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放在Employee类的部门上,并将@MappedBy写在Department类的员工列表中?

更新

那么@MappedBy和@JoinColumn如何运作?

解决方法:

实际上,似乎你没有使用@MappedBy注释,而是@OneToMany中的mappedBy =“department”.

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

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

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

关于@JoinColumn它更容易,这里你有表外键,所以你告诉hibernate这不仅是一个列,而是一个必须连接表的列.

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映射文档.

标签:java,hibernate,foreign-keys,entity-relationship
来源: https://codeday.me/bug/20190611/1221712.html