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
}
...
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);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.