0
@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;  
}
  • 我想要一个单独的表,该表与DepartmentEmployee等员工具有OneToMany关系

--------------------------
departmentId | EmployeeId
--------------------------
      1      |     1     |
      1      |     2     |
      1      |     3     |
      2      |     5     |
--------------------------
  • 我想确保有一个uniqueConstraintonDepartment.idEmployee.id

我如何做到这一点JPA

4

2 回答 2

0

使用@OneToManyon employeeswith @JoinTableannotaion。

就像是,

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

希望您不必担心这里的唯一约束,默认情况下会创建一个。但是你想提供特定的名称,你可以利用uniqueConstraints=@UniqueConstraint`JoinTable.propery。

于 2013-03-06T22:11:14.360 回答
0

使用@JoinTable, 和uniqueConstraints:

@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;  
}

警告:以上只是伪代码。

于 2013-03-06T22:11:52.397 回答