Hibernate session flush mode favorites
The first thing you need to know is:
Hibernate tries its best to delay the operation with the database until it must interact with the database. For example, the SAVE method is generally executed only when it is submitted, at the end of the submission, the database will be interacted with in batches to improve efficiency.
The operation delay is to use the cache to put the last operation to be processed into the cache.
The main function of the flush method is to clear the cache and force the database to synchronize with the hibernate cache to ensure data consistency. Its main action is to send a series of SQL statements to the database and execute these SQL statements, but they are not submitted to the database. The commit method first calls the flush method and then commits the transaction.
In the following cases, Hibernate will call session. Flush () to clear the cache:
1) when a transaction is committed, if the flush mode is not flushmode. Never, commit () will call flush ().
2) before some query statements (the statements before this query statement have changed the database status, so you need to call flush () to synchronize the data found in the database is changed ).
Unless the flush () command is explicitly specified, it cannot be guaranteed when the session will execute these JDBC calls. They can only ensure the execution order.
By setting session. setflushmode (), you can precisely control the flushmode of hibernate.
(1) flushmode. Auto: hibernate determines whether the object property has changed. If it is changed to dirty data, this change will be updated before a query statement to ensure database synchronization. This is also the default Clear mode of hibernate.
(2) flushmode. Commit: clears the session cache before the transaction ends. This may cause dirty data detection.
(3) flushmode. Never: The session will never be cleared unless session. Flush () is forcibly called. It is equivalent to setting the database as a read-only database.
[If you write data at this time, an error will occur]
(4) flushmode. Always: Session. Flush () is called before each data query (). Obviously, this efficiency is very low.
When session. Flush () is called, the SQL statements involved are executed in the following order.
(1) All the statements inserted by objects are executed in the order of session. Save.
(2) All statements for updating entities
(3) All statements for deleting, updating, or inserting collection Elements
(4) All statements that delete objects are executed in the order of session. Delete.
(5) One exception is that if an object uses the ID (persistence identifier) generated in native mode, it will be inserted as soon as it executes save.
[Because native must interact with the database if you want to obtain the primary key, but does not use Hilo ])
This article from the csdn blog, reproduced please indicate the source: http://blog.csdn.net/MageShuai/archive/2009/09/11/4544202.aspx