Reputation: 21080
Consider the following association Book has OneToMany Chapters
If i execute:
session.save(book)
session.save(chapter)
session.getTransaction().commit()
Hibernate generates insert query for Book and insert query for Chapter
But if i execute:
session.save(chapter)
session.save(book)
session.getTransaction().commit()
Hibernate executes insert query for chapter, insert query for book and update query for chapter.
Is there any way to do this in 2 inserts instead of 2 inserts and 1 update? (Assume primary key generation is similar to Identity and Chapter.Book is nullable)
Upvotes: 4
Views: 2628
Reputation: 597056
That's because you probably have Book 1..n Chapter
, with cascade
set to (at least) PERSIST
. Which means that whenever a book is saved, all of its chapters are saved as well.
So you are actually trying to save the chapters twice. You don't need the 2nd save (in the 2nd example)
The first example works that way because the chapter has become associated with the session (perhaps you haven't overridden the hashCode()
and equals()
methods), and the save()
doesn't do anything at all.
But these are all guesses. You'd have to show your mappings.
Upvotes: 5