JPA CascadeType.REMOVE not working

天大地大妈咪最大 提交于 2019-12-11 03:18:09

问题


I have two entities Business which is composed of a list of Departments

@Entity
@Table(name = "Business")
public class Business implements Serializable {

  private static final long serialVersionUID = 1L;

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = "Id")
  private Long id;

  @OneToMany(mappedBy = "business", 
       cascade = {CascadeType.PERSIST, CascadeType.REMOVE})
   private List<Department> departments;

   @OneToMany(mappedBy = "business", orphanRemoval = true, 
     cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE})
   private List<Process> processs;

   @ManyToMany
   private List<Competence> competences;
}


@Entity
@Table(name = "Department")
public class Department implements Serializable {
   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   private Long id;

   @OneToMany(mappedBy = "father", 
        cascade = {CascadeType.PERSIST, CascadeType.REMOVE})
   private List<Department> departments;
}

When I try to remove a business instance I get a Mysql Exception

Cannot delete or update a parent row: a foreign key constraint fails (evac_java.Department, CONSTRAINT FK_Department_Business FOREIGN KEY (Business) REFERENCES Business (Id)):HY000 - null

Which means I can't delete the business instance because it has departments associated with it, but a department cannot exists by itself so I want to delete all business's departments when it gets removed. I thought I would achieve this by adding cascade = CascadeType.REMOVE to the @OneToMany annotation in the business entity, but it does not work.

I did a search on the net and I found a lot of questions similar to this one on stackoverflow but they all suggest the same: add cascade = CascadeType.REMOVE or CascadeType.ALL

So I'm wondering if I'm missing somethig.

I'm using Glassfish 4.1 and EclipseLink

I tried with

@OneToMany(mappedBy = "business", orphanRemoval = true)
private List<Department> departments;

on the business entity but it does not work either

Here's the method I'm using to remove entities which is declared in an abstract class

public void remove(T entity) {
    getEntityManager().remove(getEntityManager().merge(entity));
}

回答1:


JPA can only remove and cascade the remove over entities it knows about, and if you have not been maintaining both sides of this bidirectional relationship, issues like this will arise. If the collection of departments is empty, try an em.refresh() before the remove, forcing JPA to populate all relationships so that they can be correctly removed, though it is better to maintain both sides of the relationship as changes are made to avoid the database hit.



来源:https://stackoverflow.com/questions/29733873/jpa-cascadetype-remove-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!