views:

73

answers:

1

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)

+4  A: 

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.

Bozho
You're explanation do not work for the first example : book is saved (with its chapters if there is a cascade) and then the chapter should be saved another time with your explanation, generating also an update. That's not what is happening. In the second example, i guess the first save of a chapter do not save the link to the book. The update is then generated to set the link (once hibernate know the book id).
Thierry
it does, see my update
Bozho