Reputation: 1360
I have a class, which can be referenced by many different classes in a Many-To-One or One-To-One relationship or have no referencing object. When an element of this class is deleted, the objects pointing to it should be removed too. What is the most beautiful way to achieve this behavior?
class A {
public remove() {
// remove the element which is pointing to me
}
}
class B {
@ManyToOne
private as
}
class C {
@ManyToOne
private as
}
...
Upvotes: 1
Views: 286
Reputation: 1571
First Of All, I don't think it is a 'beautiful' solution to put business methods in your entity class.
I would recommend creating DAO object for your A class and make your relationship bi-directional with CascadeType set to REMOVE:
@Entity
class A {
@OneToMany(mappedBy = "parentB", cascade = CascadeType.REMOVE)
private Set<Child> childrenB;
@OneToMany(mappedBy = "parentC", cascade = CascadeType.REMOVE)
private Set<Child> childrenC;
}
@Stateless
class daoA {
@PersistenceContext
EntityManager em;
public void remove(A a){
em.delete(a);
}
}
Upvotes: 1