The article is good. Transferred from: http://blog.csdn.net/wkcgy/article/details/6192839#
Focus:
1 The difference between flush (), clear (), evict ().
2 Hibernate execution Process
Hibernate executes in the following order:
(1) Generate a transaction object and mark the current Session in the transaction state (note: database-level transactions are not started at this time).
(2) The application uses S.save to save the object, this time the session will put this object into Entityentries, to mark the object has been associated with the current session, because the application to save the object, the session is also registered in the insertions application This insert behavior (behavior includes: object reference, Object ID, Session, persisted Class).
(3) S.evict detach the object from the S session, and S will move the object out of the entityentries.
(4) Transaction commits, all caches need to be flush into the database, Session initiates a transaction, and submits all previously registered operations in the order of Insert,update,......, Delete (note: The update will not be performed until all insert executions have completed, Special handling can also make a mess of your program, such as the need to control the order of execution of the operation, to be good at using flush), now the object is not in Entityentries, but in the execution of the insert behavior only need to access insertions is enough, So there is no exception at this time. The exception appears after the insert notifies session that the object has been inserted complete this step, this step needs to set the EXISTSINDATABASE flag of the object in Entityentries to true, because the object does not exist in Entityentries, at this time Hibernate thinks that insertions and entityentries may be out of sync because of thread-safety issues (or whether hibernate developers are considering how to handle the example, and if not, it might be a bug), so a Net.sf.hibernate.AssertionFailure is thrown and the program terminates.
In general, we will mistakenly think that S.save will execute immediately, and the object is removed prematurely from the session, resulting in the session insertions and entityentries the content of the different steps. So when we do this, it's important to know when Hibernate will flush the data into the database and not detach the manipulated object from the session until it's flush. The workaround is to add Session.flush after save.
Hibernate execution Process