如何在单独的表中实现uniqueConstraint和map?

时间:2013-03-06 22:01:58

标签: java hibernate java-ee jpa

@Entity
class Employee {
  @Column
  private UUID id;

  @Column
  private String firstName;

  @Column
  private String lastName;  

}

@Entity
class Department {
  @Column
  private UUID id;

  @Column
  private List<Employee> employees;  
}
  • 我想要一个单独的表,其中 OneToMany 部门与员工关系如 DepartmentEmployee

--------------------------
departmentId | EmployeeId
--------------------------
      1      |     1     |
      1      |     2     |
      1      |     3     |
      2      |     5     |
--------------------------
  • 我想确保uniqueConstraintDepartment.id上有Employee.id

如何在JPA中实现此目的?

2 个答案:

答案 0 :(得分:0)

利用@OneToMany employees注释@JoinTable

类似的东西,

@OneToMany
@JoinTable(name="DEPT_EMP", 
          joinColumns=@JoinColumn(name="departmentId"),
          inverseJoinColumns=@JoinColumn(name="EmployeeId"))
private List<Employee> employees;

希望您不必担心此处的唯一约束,默认情况下会创建一个。但是,如果要提供特定名称,可以使用{Join}的uniqueConstraints=@UniqueConstraint属性。

答案 1 :(得分:0)

使用@JoinTableuniqueConstraints

@Entity
class Employee {
    @Column
    private UUID id;

    @Column
    private String firstName;

    @Column
    private String lastName;
}

@Entity
class Department {

    @OneToMany
    @JoinTable(joinColumn = @JoinColumn(name = "employee_id"), 
        inverseJoinColumn(name = "department_id"),
        uniqueConstraints=@UniqueConstraint(columnNames={"employee_id", "department_id"}))
    private List<Employee> employees;  
}

警告:以上只是伪代码。