如何在保持数据库处于一致状态的同时使用JPA删除行

时间:2015-01-07 20:40:53

标签: java jpa

我想用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;

    ...

1 个答案:

答案 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