Hello all. I have looked through the forums and so far have not been able to find a similar situation so hopefully this is not a duplicate. This is also my first post so I apologize in advance for the format. The machine that contains the code does not have access to the internet so the below code is a brief snippet of what is relevant. if I missed something of relevance please let me know :)
I have the following table structure which cannot be changed in our database:
Code:
------------------- Child_A
| child_id
|
|
Parent --------------- Parent_Child ---------- Child_B
parent_id parent_id child_id
child_id
|
|
------------------ Child_C
child_id
The jist of it is that the parent table uses the same join table for its association with several different child tables. The Parent table is mapped as follows (The ManyToMany is because there is no unique constraint for either column in the join table):
Code:
@Entity
@Table(name = "Parent")
public class Parent implements Serializable
{
@ManyToMany(cascade = {CascadeType.All})
@JoinTable(name = "Parent_Child",
joinColumns = {@JoinColumn(name = "parent_id", referencedColumname = "parent_id")},
inverseJoinColumns = {@JoinColumn(name = "child_id", referencedColumnName = "child_id")})
private Set<ChildA> childrenA;
@ManyToMany(cascade = {CascadeType.All})
@JoinTable(name = "Parent_Child",
joinColumns = {@JoinColumn(name = "parent_id", referencedColumname = "parent_id")},
inverseJoinColumns = {@JoinColumn(name = "child_id", referencedColumnName = "child_id")})
private Set<ChildB> childrenB;
...
}
Each of the children are mapped as follows:
Code:
@Entity
@Table(name = "Child_A")
public class ChildA implements Serializable
{
@ManyToMany(mappedBy = "childrenA")
private Set<Parent> parents;
...
}
@Entity
@Table(name = "Child_B")
public class ChildB implements Serializable
{
@ManyToMany(mappedBy = "childrenB")
private Set<Parent> parents;
...
}
Now assume the following code:
Code:
...
Parent parent = new Parent();
parent.setId(id1);
ChildA childA1 = new ChildA();
childA1.setId(id2);
ChildB childB1 = new ChildB();
childB1.setId(id3);
parent.getChildrenA().add(childA1);
parent.getChildrenB().add(childB1);
session.save(parent);
At this point, everything is fine. I see the inserts into Parent_Child for both relationships. However the problem appears when performing a delete:
Code:
...
parent.getChildrenA().clear();
session.update(parent);
At this point, the generated SQL performs a one-shot delete and actually removes the relationships to both child A and child B. From what I read, hibernate will optimize when it detects an empty collection so instead of
Code:
delete from Parent_Child where parent_id = ? and child_id = ?
I am seeing
Code:
delete from Parent_Child where parent_id = ?
Is there any way around this? Any help on the matter is greatly appreciated.
Thanks,
Matthew