我喜欢删除一个实体,该实体将被另一个实体引用。 这是我的测试:
@Entity
@DiscriminatorValue("Teacher")
public class Teacher extends Employee{
@Id @GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private Teacher(){
}
@OneToMany(cascade = {CascadeType.PERSIST, CascadeType.REMOVE})
private List<SchoolSubject> schoolSubjects;
}
@javax.persistence.Entity
@DiscriminatorValue("SchoolSubject")
public class SchoolSubject implements Resource{
@Id
private String name; // Name of the schoolsubject has to be unique
@Override
public Long getID() {
return id;
}
public SchoolSubject(){}
public SchoolSubject(String name)
{
this.name = name;
}
}
所以我尝试删除所有 SchoolSubjects:
q = em.createQuery("select ss from SchoolSubject ss");
List<SchoolSubject> subjects = q.getResultList();
for(SchoolSubject subject:subjects)
{
em.getTransaction().begin();
em.remove(subject);
em.getTransaction().commit();
}
所以我知道这个操作不会起作用,因为老师引用了 SchoolSubjects。 - 我喜欢“删除”SchoolSubject 以及教师列表中的 SchoolSubject。
例如: 1. 删除SchoolSubject 2. 教师搜索该“SchoolSubject”,如果找不到则自动从列表中删除SchoolSubject。
最佳答案
我的解决方法是使用 ManyToMany 关系。 因此,我迭代 SchoolSubject 中的教师,并为每位教师删除该主题。 在此步骤之后,我从 SchoolSubject 内的列表中删除该教师。
关于java - JPA持久化: Automatical remove of not existing referenced entity from list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26827287/