Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring JPA repository delete method doesn't work

I can't get Spring JPA to delete bar entity with jpa repository delete method.
Can anyone see where the problem is?

doesn't work:

barRepository.delete(bar.id);

Jpa repository:

public interface BarRepository extends JpaRepository<Bar, Integer>

Hibernate entity mappings (only relevant parts):

@Entity(name = "foo")

@OneToMany(fetch = FetchType.EAGER, mappedBy = "foo", cascade = CascadeType.ALL, orphanRemoval = true)
@Fetch(FetchMode.SELECT)
private List<Bar> bars = new ArrayList<>();

@Entity(name = "bar")

@ManyToOne(optional = false)
@JoinColumn(name = "foo_id")
@Fetch(FetchMode.SELECT)
private Foo      foo;

EDIT: git repo with minimal reproducible example. HibernateDeleteApplicationTests.java contains test case.

https://github.com/matijaivanus/hibernate-delete-problem

like image 240
redMist Avatar asked Sep 06 '25 03:09

redMist


1 Answers

The "problem" is your mapping. Your collection is retrieved eagerly. Now why would that be an issue. The deleteById in Spring Data JPA first does a findById which in your case loads the Bar and the Foo and eagerly the collection inside Foo.

Now the Bar is attempted to be deleted but due to it being still attached and referenced by another entity it would be persisted again, hence the delete is cancelled.

To solve you have 3 options

  1. Delete using a query and write your own query method for this
  2. Properly remove the Bar from Foo, set the relation to null and then persist Foo or delete Bar.
  3. Mark either side of the assocation lazy (this still can fail due to 1).

Either of these will work. The first one because it bypasses the JPA caching mechanisms, the second because now the association has been cut. The third can work but if the objects have already been loaded run into the same issue as 1.

like image 99
M. Deinum Avatar answered Sep 07 '25 23:09

M. Deinum