@JoinColumn和@MappedBy如何工作

时间:2015-09-07 13:47:22

标签: java hibernate foreign-keys entity-relationship

我对@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<>();
}

我在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放在department Employee class上,然后在MappedBy list of employees上写{@ 1}} ?

更新

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

1 个答案:

答案 0 :(得分:8)

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

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

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

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

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

  

使用@JoinColumn注释声明连接列,该注释类似于@Column注释。它还有一个名为 referencedColumnName 的参数。此参数声明将用于连接的目标实体中的列。请注意,将 referencedColumnName 用于非主键列时,关联的类必须是Serializable。另请注意,非主键列的 referencedColumnName 必须映射到具有单个列的属性(其他情况可能不起作用)。

查找HERE hibernate地图文档。