I am working on import functionality where in i have to import data from a file and update it to the database using hibernate.
The object structure is : there is a parent and it has a Set of children.
When i do the import i first delete all the existing children and then add the new children i read from the file.
The way i do it is as below
parent = session.load(<id of parent>)
parent.getchildrenSet.clear()
parent.saveOrUpdate(parent);
Then, in a loop create new children and add it to the childrenSet on the parent. Then
parent.saveOrUpdate(parent);
Mappings are as below
In Parent
@OneToMany(cascade = CascadeType.ALL)
@JoinTable(name = "CHILD_TABLE", joinColumns = { @JoinColumn(name = "CHILD_PARENT_ID") }, inverseJoinColumns = { @JoinColumn(name = "CHILD_ID") })
@MapKeyColumn(name = "CHILD_ID")
private Map<Long, Children> childrenMap;
In the Child
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "CHILD_PARENT_ID")
private Parent parent;
When i run this code i expected the logs to print the DMLs in the below order
1. Delete all the children
2. Insert new children
3. Update the parent
But what it prints is
1. Insert new children
2. Update the parent
3. Delete all the children
So, as a result of the above order, it removes all the children from the parent, even the ones which i added newly because of import.
It seems like hibernate doesnt maintain the order in which i had called the DMLs. Can anyone provide me some suggestions on this? Let me know if the question is not clear.
Collections.clear() doesn’t equate to delete. You need to call an explicit delete to ensure you delete before you insert. Else, the implicit delete will get exexuted when your session terminates.