Spring Data JPA Deletes Child Entity Only When Parent is LAZY Fetched

Viewed 53

I have a user class which has a field:

@OneToMany(mappedBy = "user", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
@JsonManagedReference
private Set<FavoriteProduct> favoriteProducts = new HashSet<>();

Favorite product class has that field:

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "users_id", nullable = false)
@JsonBackReference
private User user;

When I try to delete a favorite product via a favorite product repository which extends a JpaRepository it is not successfull.

However, it works when I change EAGER fetch to LAZY fetch as follows:

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "users_id", nullable = false)
@JsonBackReference
private User user;

What can be the reason for that?

1 Answers
  • Hibernate will not delete a child object if that object is referenced from a parent object.

  • With FetchType.EAGER, you are initializing the association with the parent too.

  • With FetchType.LAZY, the user association will not be loaded unless you try to access the user in the persistence context.

  • You can try to access the user first before deleting. It should emulate the similar behavior even with FetchType.LAZY

Related