Situation: Got Books and categories. Each category can have n books. Want to create new, update or delete books from category. If category is empty delete it from db. Currently insert, update, and delete books.
Problem: orphanRemoval=true doesn't delete category if it is empty.
@Entity
@Table(name = "book")
@Getter
@Setter
public class BookEntity implements DBEntity, Serializable {
@Id
private Integer id;
private String bookname;
@ManyToOne(cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.DETACH, CascadeType.REFRESH})
@JoinColumn(name = "categoryid", referencedColumnName = "id")
private CategoryEntity categoryEntity;
public Integer getId() {
return this.id;
}
}
@Entity
@Table(name = "category")
@Getter
@Setter
public class CategoryEntity implements DBEntity, Serializable {
@Id
private Integer id;
private String categoryName;
@OneToMany(cascade = CascadeType.REMOVE, mappedBy = "categoryEntity", orphanRemoval = true)
private Set<BookEntity> bookEntitySet = new HashSet<BookEntity>(0);
}
@Transactional
public interface CategoryDAO extends CrudRepository<CategoryEntity, Integer> {
}
@Transactional
public interface BookDAO extends CrudRepository<BookEntity, Integer> {
}
Thanks for any help
p.s.
Tried:
didnt help:
Spring + JPA @OneToMany with orphanRemoval
looks stupid - deleting book from category (in case 2-n foreign key wont work):
https://hellokoding.com/jpa-one-to-many-relationship-mapping-example-with-spring-boot-maven-and-mysql/
Nothing mentioned:
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/