Reputation: 5926
I have an unidirectional mapping from child to parent by @ManyToOne like this:
@ManyToOne()
@JoinColumn(name = "PARENT_ID")
private ParentEntity parent;
I it possible to remove parent, when last child is removed without having reference from ParentEntity to ChildEntities? None of the annotations I tried seems to be working.
Upvotes: 3
Views: 1328
Reputation: 2095
AFAIK there is no method from jpa to do this. But you can check the number of child entitys in your service in the deletion method and than delete parent if it was the last.
Upvotes: 1
Reputation: 974
No, you can not do it only with annotation: hibernate does not know about first, second or last child. To solve task you can write @PostRemove
interceptor (in jpa, or listener in hibernate), in which calculate case "last child", call entity manager and remove parent. Do DAO operation in entity is not perfect, but if you really want....
Upvotes: 2