Armando
Armando

Reputation: 471

JPA CascadeType.REMOVE not working

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));
}

Upvotes: 2

Views: 14163

Answers (1)

Chris
Chris

Reputation: 21145

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.

Upvotes: 3

Related Questions