Hi.
Back to basics, this is a very
simple scenario, but I couldn't find the good way to solve it, only using hucks.
I have one object A, which contains 3 collections for B, C, D. Here is the example of mappings for one of them:
Code:
@OneToMany(mappedBy = "contractCharges", fetch = FetchType.LAZY)
@Cascade( { CascadeType.DELETE_ORPHAN})
@Sort(type = SortType.NATURAL)
private SortedSet<ContractExpenseEstimate> expenseEstimates = new TreeSet<ContractExpenseEstimate>();
In the UI I create the object A and collections for B, C and D for it. Then try to save the object A and all its collections:
Code:
session.save(A); (1)
for(B b: A.getB()) {
session.save(b);
}
for(C c: A.getC()) {
session.save(c);
}
for(C c: A.getC()) {
session.save(c);
}
tx.commit();
But I fail to do the (1) operation due to
object references an unsaved transient instance: A.B exception. I know, that Hibernate requires all referent objects to be persistent, but anyway cannot understand why doesn't save A, get its id and use it for dependencies??? And why this piece of code works ok?:
Code:
// Cloning dependencies to another array, cleaning them in A and persisting A. Then adding copies back to A :(
List<B> copyOfB = new ArrayList<B>(A.getB());
A.getB().clear();
// The same two actions for C and D
session.save(A);
for(B b: copyOfB) {
A.getB().add(b);
b.setParent(A);
session.save(b);
}
// The same for C and D...
tx.commit();
Nonsense! This is really bad code, but I have not found any other workarounds... CascadeType.SAVE_UPDATE does not suit for me, cause I want to update only CHANGED dependencies, not the whole bunch of them and produce bulk of updates after each small change.
Any opinion is welcomed :)