@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;
}
--------------------------
departmentId | EmployeeId
--------------------------
1 | 1 |
1 | 2 |
1 | 3 |
2 | 5 |
--------------------------
uniqueConstraint
和Department.id
上有Employee.id
如何在JPA
中实现此目的?
答案 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)
使用@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;
}
警告:以上只是伪代码。