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
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
Bar from Foo, set the relation to null and then persist Foo or delete Bar.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With