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.
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);