试图理解@JoinTable和@JoinColumn是如何工作的

时间:2016-08-19 13:15:01

标签: java hibernate jointable

我正在学习休眠,并且遇到了以下问题

有两张桌子

CREATE TABLE department (
 department_id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
 caption varchar(255) DEFAULT NULL) ENGINE=InnoDB;
CREATE TABLE employee (
 employee_id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
 fio varchar(255) DEFAULT NULL,
 fk_department_id int(11) NOT NULL,
 FOREIGN KEY (fk_department_id) REFERENCES department (department_id) 
) ENGINE=InnoDB ;

和两个类(在第一个类中注释掉的代码看起来像工作解决方案)

@Entity
@Table(name = "department")
public class Department {
....
    @OneToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "employee", joinColumns = {
            @JoinColumn(name = "fk_department_id", referencedColumnName = "department_id") })
    /*
     * @OneToMany(fetch = FetchType.LAZY, mappedBy = "department", cascade =
     * CascadeType.ALL)
     */
    public Set<Employee> getEmployies() {
        return employees;
    }
@Entity
@Table(name = "employee")
public class Employee {
......
    @ManyToOne
    @JoinColumn(name = "fk_department_id")
    public Department getDepartment() {
        return department;
    }

这导致

INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
Exception in thread "main" org.hibernate.MappingException: Foreign key (FK3cspe1b06hmsik5l8y1i11xmd:employee [employies_employee_id])) must have same number of columns as the referenced primary key (employee [fk_department_id,employies_employee_id])
    at org.hibernate.mapping.ForeignKey.alignColumns(ForeignKey.java:148)
    at org.hibernate.mapping.ForeignKey.alignColumns(ForeignKey.java:130)

请帮助我理解为什么这不起作用

1 个答案:

答案 0 :(得分:1)

以下应该可以正常工作。您会注意到我没有指定任何连接列关系,因为我允许Hibernate自动为我生成这些关系。

T

但是我们假设你想明确关于连接列。

@Entity
public class Department {
  @OneToMany
  @JoinTable(name = "department_employees")
  private List<Employee> employees;
}

@Entity
public class Employee {
  @ManyToOne
  private Department department;
}

要脱离这一点的关键点是:

  • 连接表的名称指定维护@Entity public class Department { @Id @Column(name = "department_id") private Integer id; @OneToMany @JoinTable( name = "department_employees", joinColumns = @JoinColumn(name = "department_id"), inverseJoinColumns = @JoinColumn(name = "employee_id")) private List<Employee> employees; } @Entity public class Employee { @Id @Column(name = "employee_id") private Integer id; @ManyToOne @JoinTable( name = "department_employees", joinColumns = @JoinColumn(name = "department_id", insertable = false, updatable = false), inverseJoinColumns = @JoinColumn(name = "employee_id", insertable = false, updatable = false)) private Department department; } Department实体之间关系的中间表。它不应该像您的代码所示,引用Employee表。
  • Employee属性表示包含实体的主键属性,在本例中为joinColumns,因此我使用了Department
  • department_id属性表示关联实体的主键属性,在本例中为inverseColumns,因此我使用了Employee

更新

如果您想要删除employee_id并仅保留@JoinTableDepartment之间的关系,则可以按如下方式更改映射:

Employee

希望有所帮助。