Reputation:
When I want to delete a parent in Hibernate, if there is child is there a mechanism that throws an exception?
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "categoryId")
private Category category;
@OneToMany(mappedBy = "category", cascade = CascadeType.ALL)
private List<Product> productList = new ArrayList<>();
not delete category, if the product belongs to the category.
Upvotes: 0
Views: 56
Reputation: 2029
Why would Hibernate throw an exception on category delete that contains products? You're asking Hibernate to do it by defining cascade = CascadeType.ALL
.
If you don't want a category to be deleted when it contains some products you need to make sure of it by yourself:
if (category.containsProducts()) {
throw new Exception();
}
categoryRepository.delete(category);
Upvotes: 1