简体   繁体   中英

Hibernate - controlling Insert and Update Queries

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM