Nitek Nitek - 1 month ago 10
Java Question

Spring Data Repository does not delete ManyToOne Entity

I'm am currently trying to use a Spring Data repository to delete some of my entities. The delete call works without any exceptions/error messages, but the entity is not deleted afterwards.

Those are my entities:

public class Board implements Serializable {

@GeneratedValue(generator = "uuid2")
@GenericGenerator(name = "uuid2", strategy = "uuid2")
@Column(columnDefinition = "BINARY(16)")
private UUID uuid;

@OneToMany(fetch=FetchType.EAGER, cascade=CascadeType.ALL, orphanRemoval = true, mappedBy = "board")
private List<Post> posts = new ArrayList<Post>();


public class Post implements Serializable {

private long id;

@ManyToOne(optional = false)
@JoinColumn(name="board_uuid", updatable = false, nullable = false)
private Board board;

The repository is as simple as it can be:

public interface PostRepository extends CrudRepository<Post, Long> {

The delete call is something like


Any ideas why this change doesn't reflect in the database?

Edit 1:

I found a workaround, but I still don't understand what the real problem is.
It "works" if I delete the Post like this (there are a couple of exceptions because of constraint violations, but still the Post gets deleted):


Edit 2:

When I have a look at the SQL statements executed I can see that hibernate is not even trying to delete. The only thing that happens are those two select statements:

Hibernate: select as id1_1_0_, post0_.board_uuid as board_uu6_1_0_, post0_.content as content2_1_0_, post0_.x as x3_1_0_, post0_.y as y4_1_0_, post0_.z as z5_1_0_, board1_.uuid as uuid1_0_1_ from Post post0_ left outer join Board board1_ on post0_.board_uuid=board1_.uuid where
Hibernate: select posts0_.board_uuid as board_uu6_0_0_, as id1_1_0_, as id1_1_1_, posts0_.board_uuid as board_uu6_1_1_, posts0_.content as content2_1_1_, posts0_.x as x3_1_1_, posts0_.y as y4_1_1_, posts0_.z as z5_1_1_ from Post posts0_ where posts0_.board_uuid=?

Edit 3

Turns out the cascade=CascadeType.ALL on posts seems to be the problem. Without it the delete works fine (but I am missing the cascade of changes to posts now)


The problem seems to be that you are using cascade=CascadeType.ALL, which also includes CascadeType.PERSIST. CascadeType.PERSIST means that the child entity is completely managed by the parent and you cannot delete it directly. In order to delete you just need to remove it from the parent.

You could just add the other CascadeTypes instead of all. e.g CascadeType.REMOVE, if the only thing you would want is to remove the child if the parent is removed.