Persistence context cache the id and SQL query?

匿名 (未验证) 提交于 2019-12-03 01:45:01

问题:

If one call session.save(customerObject) then there is no insert into customer… query into the database. Hibernate will set the id property ("sequence" or "Increment" generator) and bind the entity to a persistence context. The persistence context is synchronized with the database when transaction.commit() is called.
Q: where will Hibernate set the id property?
Q: will the persistence context cache the sql query insert into customer… before synchronized with db ? I mean,when does sql generated(while doing save or session.flush/tx.commit)

EDIT: I got below from https://forum.hibernate.org/viewtopic.php?t=951275&highlight=difference%20persist%20save

persist() is well defined. It makes a transient instance persistent. However, it doesn't guarantee that the identifier value will be assigned to the persistent instance immediately, the assignment might happen at flush time. The spec doesn't say that, which is the problem I have with persist().

persist() also guarantees that it will not execute an INSERT statement if it is called outside of transaction boundaries. This is useful in long-running conversations with an extended Session/persistence context.

A method like persist() is required.

save() does not guarantee the same, it returns an identifier, and if an INSERT has to be executed to get the identifier (e.g. "identity" generator, not "sequence"), this INSERT happens immediately, no matter if you are inside or outside of a transaction. This is not good in a long-running conversation with an extended Session/persistence context.

This is more confusing

回答1:

In general, Hibernate tries to write to the database as latest as possible, without compromising the correctness of the program, and by respecting the contract of the methods it offers.

Since save() is documented to assign an ID to the saved entity and return this ID, it generates the ID when save() is called, and returns it. This might mean that the entity is written to the DB or not, depending on the ID generation strategy.

Since persist() doesn't guarantee that an identifier is assigned when it's called, then you can't count on an ID to be assigned after persist() has been called. And you can't expect the entity to be written to the DB either, since that's not what persist() does. It's as simple as that.

Writes to the DB are only guaranteed to be executed when the session is flushed, automatically before the commit, or explicitely when flush() is called. You also have the guarantee that a write to the DB is executed if you execute a query whose results might depend on the pending writes.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!