我想用JPA创建一个数据库。我的问题是我无法弄清楚如何配置实体:
我有两个实体,如:
@Entity(name = "PROJECTS")
public class Project implements Serializable {
...
@ManyToMany(fetch=FetchType.EAGER)
@JoinTable(name="PROJ_EMPL",
joinColumns=
@JoinColumn(name="PROJECT_ID", referencedColumnName="PROJECT_ID"),
inverseJoinColumns=
@JoinColumn(name="EMPLOYEE_ID", referencedColumnName="EMPLOYEE_ID")
)
private List<Employee> employeeList;
...
@Entity(name = "EMPLOYEES")
public class Employee implements Serializable {
...
@ManyToMany(mappedBy="employeeList",fetch=FetchType.EAGER)
private List<Project> projectList;
...
答案 0 :(得分:0)
正如评论中所述,我不认为你可以单独利用JPA这样做,我认为它不可能。
从概念上讲,您指定的内容是Project
的不变量:&#34; employeeList
中至少有一名成员。&#34;
我喜欢保护自己不变量的实体,也许是这样:
public class Project {
@ManyToMany
private List<Employee> employeeList = new ArrayList<>();
private Project(){ } /* we need this for Hibernate */
public Project(Collection<Employee> initialMembers) {
employeeList.addAll(initialMembers);
}
public boolean removeEmployee(Employee e) {
if (employeeList.size() <= 1) return false;
employeeList.remove(e);
return true;
}
public int employeesCnt() {
return employeeList.size();
}
}
应用程序逻辑需要实现您的要求:
public ProjectController {
private Project instance = /* get your project somehow */;
@Transactional
public void reduceEmployeeCnt() {
if (!instance.removeEmployee()) {
jpaSession.remove(instance);
}
}
}
另一种方式是EntityListener @PreRemove
,如描述here。