Hello everybody, I have a problem with an object related (through a list) to two different objects. Bellow is a model of the problem: @Entity @Table(name = "table1", schema = "public") public class Class1 implements java.io.Serializable { .... @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "parent") public List<ObjectComponent> getObjectComponents() { return this.objectComponents; }
public void setObjectComponents(List<ObjectComponent> objectComponents) { this.objectComponents = objectComponents; } .... }
@Entity @Table(name = "table2", schema = "public") public class Class2 implements java.io.Serializable { .... }
@Entity @Table(name="object_components" ,schema="public" ) public class ObjectComponent implements java.io.Serializable {
private Object1 parent; private Object2 child; .....
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER) @JoinColumn(name="parent_id") public Object2 getChild() { return this.child; } public void setChild(Object2 child) { this.child = child; }
@ManyToOne(fetch=FetchType.EAGER) @JoinColumn(name="child_id") public Object1 getParent() { return this.parent; }
public void setParent(Object1 parent) { this.parent = parent; } ... }
Nothing in this model prevents me from including the same instance of Object2 in to two different lists of two different instances of Object1. Indeed my business model requires this. But here is a problem: When I delete the first instance of Object1, the one and only instance of Object2 will be deleted because of the "cascade" clause. But it is not what I want. I want it to be deleted only if there is no other objects that it belongs to.
My question is can I achieve the required behavior through correct setting, or I have to remove the "cascade" clause altogether and to deletion manually?
The same problem arises when I try to "evict" the first instance of Object1. The instance of Object2 became evicted and successful reading the second instance of Object1 fails.
Again my question is: how to fight this and other problems, created by above object structure, naturally for Hibernate, instead of using brute force?
Thank you, Lev Tannen
|