Skip to content
Advertisement

Delete cascade Category child (Java Hibernate JPA)

I have this Entity to represent a Category system with a selfrelationship to get child categories:

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

@Column(unique = true)
private String nombre;

private String descripcion;

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "codigo_categoria_padre")
@JsonBackReference
private Categoria categoriaPadre;

@OneToMany(mappedBy = "categoriaPadre", fetch = FetchType.EAGER, cascade = CascadeType.REMOVE, orphanRemoval = true)
private List<CategoriaExtends> categoriasHijas;

The problem is when I want to delete a category that has child categories. I want to delete all child categories but Java drops me this exception :

Cannot delete or update a parent row: a foreign key constraint fails (vanger.producto, CONSTRAINT FKju4fpj8umbyi05750yjm70cx0 FOREIGN KEY (codigo_categoria) REFERENCES categoria (codigo_categoria))

I tried to changing some things like orphanRemoval=true or cascade = CascadeType.REMOVE or trying to put the cascade in a separated annotation but is not working.

My last hope to get this on work is deleting category childs recursively manually, but is not the proper way.

Thanks in advance 🙂

Advertisement

Answer

You should show us how you delete a category but I think the problem is that you are not removing the category from both sides of the associations:

Categoria categoria = ...

// Remove association with children
for ( CategoriaExtends child : categoria.getCategoriasHijas() ) {
   child.setCategoriaPadre(null);
}
categoria.getCategoriasHijas().clear();
entityManager.remove(categoria);
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement