Understand the flush of hibernat)

Source: Internet
Author: User

* SessionFlush:

* The session flush method mainly involves two tasks:

Clear temporary records

Execute SQL

* When is the session flush?

By default, when a transaction is committed (commit)

Display call flush

Before executing a query, for example, iterate

Hibernate submits related operations in the order of save (insert), update, and delete

 

!! As long as the transaction does not have a commit, it can be rolled back at any time !!

 

All statuses apply:

Flush: Clear temporary records !!!!!

ElementData temporary data, entryArray cache data: data is only available after saving !! Related to three States

When calling commit, flush () is first executed by default ()

 

Uuid: flush to clear temporary records during commit

After saving: hientdata is allocated with a 32 string with no records in the database. elementData temporary record: data, entryArray cache: Record, existsInDatabase: flase, which is included in session management.

[If the session is executed at this time. evict (user); // evicted from the cache. Records in the cache are cleared, but the temporary set is not cleared. then execute commit. When the temporary set is found to have data during the flush operation, insert will be sent, and then the cache record will be searched to change the existsInDatabase status to true, because the cache is cleared (and existsInDatabase is gone ), so there is a problem, throwing an exception] [solution to the above problem: After saving (), execute flush (send SQL, clear the temporary set, find the cache, change the esistsInDatabase status), and then execute eviction, clear the cache, execute commit, and find the temporary set with no data. If there is any data, send the SQL statement, and it has been flushed, so there is no data and no SQL statement is sent]

After flush: Clear the temporary set, send SQL, existsInDatabasse: true, the temporary set has no data, but the MySQL database cannot be found due to the isolation level. There are records in the cache.

After commit: The data cannot be rolled back. By default, commit will execute flush () first, so you do not need to display the call.

 

Native: save to clear temporary records

After saving: Execute the insert statement to clear temporary records. Returns the id generated by the database, which is included in session management because the cached map contains records, where: id is returned by the database. There is no record in the temporary data (it will never be seen: There is no save before save, and it is only available in the save process. Once the SQL temporary record is sent, there will be no record)

[In this case, run session. evict (user). No problem. It is different from uuid !!!]

After flush: the temporary record is cleared when saving

After commit: data cannot be rolled back

 

No matter what the policy is: Execute commit () will first execute flush () by default, after commit (), data cannot be rolled back !!

 

Assigned: the flush condition is the same as that of uuid, because the id new object is provided and does not need to be retrieved from the database.

Uuid is automatically generated by Hibernate and does not need to be retrieved from the database.

Public void testSave3 (){

Session session = null;

Transaction tx = null;

Try {

Session = HibernateUtils. getSession ();

Tx = session. beginTransaction ();

// Transient Instantaneous State

User3 user = new User3 ();

User. setId ("0001 ");

User. setName ("Zhang San ");

Session. save (user );

User. setName ("Wang Wu ");

Session. update (user); // This row can be left empty, because it is in a persistent state and Hibernate will automatically synchronize

User3 user3 = new User3 ();

User3.setId ("002 ");

User3.setName ("Li Si ");

Session. save (user3 );

System. out. print ("hell ");

Tx. commit (); // send the SQL statement at this time. hibernate submits the related operations in the order of save (insert), update, and delete, and the preceding sequence is: save, update, and save. Insert, insert, and update are sent sequentially. // If session. flush () is run before user. setName ("");, two SQL statements are run first, and then an insert statement is run when the commit statement is run. All, the SQL statement is executed in the order we want.

} Catch (Exception e ){

E. printStackTrace ();

Tx. rollback ();

} Finally {

HibernateUtils. closeSession (session );

}

}

 

Database isolation level: solves concurrency Problems

 

Whether there are dirty reads at the isolation level, whether there are non-repeated reads, and whether there are Phantom reads

Read Unommited (uncommitted Read) Y

Read Commited (commit Read, Oracle default) n y is related to the pessimistic lock Y

Repeatable Read (Repeatable, MySql Default) N Y

Serialiazble (serialized read) N

Isolation level to high: MySQL isolation level is higher than Oracle

Serialized read: The worst concurrency, exclusive to one person!

Dirty read: No data submitted

Repeatable read: The first read is Michael Jacob, And the last refresh is Lily. the pessimistic lock becomes repeatable.

Phantom read: insert operations are affected. A reads 5 Records, refreshes to 10 records, and adds 5 Records.

Serialized read: locks the table, so it is impossible for others to add data.

 

View the isolation level of mysql: select @ tx_isolation; the default level is repeatable, which can be viewed only after it is submitted.

Change the isolation level to uncommitted read: set transaction isolation level read uncommitted

 

 

Package com. guojie. hibernate;

 

Import java. util. Date;

 

Import org. hibernate. Session;

Import org. hibernate. Transaction;

 

Import com. guojie. hibernate. HibernateUtils;

Import com. guojie. hibernate. User1;

Import com. guojie. hibernate. User2;

Import com. guojie. hibernate. User3;

 

Import junit. framework. TestCase;

 

 

Public class SessionFlushTest extends TestCase {

/**

* Test the uuid primary key generation policy.

*/

Public void testSave1 (){

Session session = null;

Transaction tx = null;

Try {

Session = HibernateUtils. getSession ();

Tx = session. beginTransaction ();

 

User1 user = new User1 ();

User. setName ("Li Si ");

User. setPassword ("123 ");

User. setCreateTime (new Date ());

User. setExpireTime (new Date ());

// Because the user's primary key generates a lateral path using uuid, after saving is called, the user is only included in session management.

// The insert statement is not issued, but the id has been generated. The existsInDatebase status in the session is false.

Session. save (user );

// Call flush. hibernate clears the cache and executes the SQL statement.

// If the database isolation level is set to commit read, we can see flush data

// And the existsInDatebase status in the session is true

Session. flush ();

// Submit the transaction

// By default, the commit operation will first execute flush to clear the cache, so you do not need to call flush explicitly.

// Data cannot be rolled back after commit

Tx. commit ();

} Catch (Exception e ){

E. printStackTrace ();

Tx. rollback ();

} Finally {

HibernateUtils. closeSession (session );

}

}

/**

* Test the native primary key generation policy.

*/

Public void testSave2 (){

Session session = null;

Transaction tx = null;

Try {

Session = HibernateUtils. getSession ();

Tx = session. beginTransaction ();

 

User2 user = new User2 ();

User. setName ("James 1 ");

User. setPassword ("123 ");

User. setCreateTime (new Date ());

User. setExpireTime (new Date ());

// Because the user's primary key generation policy is native, after session. save is called, The insert statement is executed and the database id is returned.

// Manage the session and modify the existsInDatebase status in the session to true.

// If the database isolation level is set to commit read, we can see the saved data

Session. save (user );

Tx. commit ();

} Catch (Exception e ){

E. printStackTrace ();

Tx. rollback ();

} Finally {

HibernateUtils. closeSession (session );

}

}

/**

* Test the uuid primary key generation policy.

*/

Public void testSave3 (){

Session session = null;

Transaction tx = null;

Try {

Session = HibernateUtils. getSession ();

Tx = session. beginTransaction ();

 

User1 user = new User1 ();

User. setName ("Wang Wu ");

User. setPassword ("123 ");

User. setCreateTime (new Date ());

User. setExpireTime (new Date ());

// Because the user's primary key generates a lateral path using uuid, after saving is called, the user is only included in session management.

// The insert statement is not issued, but the id has been generated. The existsInDatebase status in the session is false.

Session. save (user );

// Evicted the user object from the session, that is, the EntityEntries attribute of the session.

Session. evict (user );

// Failed to submit because hibernate extracts the user object from the insertions set of the session during cache cleaning and performs the insert operation.

// You need to update the existsInDatabase in the entityEntries attribute to true, and we use evict to extract the user from the entityEntries of the session

// The data is evicted, so no relevant data can be found and cannot be updated. An exception is thrown.

Tx. commit ();

} Catch (Exception e ){

E. printStackTrace ();

Tx. rollback ();

} Finally {

HibernateUtils. closeSession (session );

}

}

/**

* Test the uuid primary key generation policy.

*/

Public void testSave4 (){

Session session = null;

Transaction tx = null;

Try {

Session = HibernateUtils. getSession ();

Tx = session. beginTransaction ();

 

User1 user = new User1 ();

User. setName ("Wang Wu ");

User. setPassword ("123 ");

User. setCreateTime (new Date ());

User. setExpireTime (new Date ());

// Because the user's primary key generates a lateral path using uuid, after saving is called, the user is only included in session management.

// The insert statement is not issued, but the id has been generated. The existsInDatebase status in the session is false.

Session. save (user );

// After flush, hibernate clears the temporary set, saves the user object to the database, and saves the user object in insertions in the session.

// Clear and set the existsInDatebase status in the session to true

Session. flush ();

// Evicted the user object from the session, that is, the EntityEntries attribute of the session.

Session. evict (user );

// The object can be submitted successfully because the user object cannot be found in the insertions set of the session when hibernate clears the temporary set.

// Therefore, the insert statement will not be issued, nor the existsInDatabase status in the session will be updated.

Tx. commit ();

} Catch (Exception e ){

E. printStackTrace ();

Tx. rollback ();

} Finally {

HibernateUtils. closeSession (session );

}

}

/**

* Test the native primary key generation policy.

*/

Public void testSave5 (){

Session session = null;

Transaction tx = null;

Try {

Session = HibernateUtils. getSession ();

Tx = session. beginTransaction ();

 

User2 user = new User2 ();

User. setName ("James 11 ");

User. setPassword ("123 ");

User. setCreateTime (new Date ());

User. setExpireTime (new Date ());

// Because the user's primary key generation policy is native, after session. save is called, The insert statement is executed and the database id is returned.

// Manage the session and modify the existsInDatebase status in the session to true.

// If the database isolation level is set to commit read, we can see the saved data

Session. save (user );

// Evicted the user object from the session, that is, the EntityEntries attribute of the session.

Session. evict (user );

// The object can be submitted successfully because the user object cannot be found in the insertions set of the session when hibernate clears the cache.

// Therefore, the insert statement will not be issued, nor the existsInDatabase status in the session will be updated.

Tx. commit ();

} Catch (Exception e ){

E. printStackTrace ();

Tx. rollback ();

} Finally {

HibernateUtils. closeSession (session );

}

}

/**

* Test the assigned primary key generation policy.

*

*/

Public void testSave6 (){

Session session = null;

Transaction tx = null;

Try {

Session = HibernateUtils. getSession ();

Tx = session. beginTransaction ();

 

User3 user = new User3 ();

User. setId ("001 ");

User. setName ("Zhang San ");

Session. save (user );

User. setName ("Wang Wu ");

Session. update (user );

User3 user3 = new User3 ();

User3.setId ("002 ");

User3.setName ("Li Si ");

Session. save (user3 );

// Hibernate: insert into t_user3 (name, password, create_time, expire_time, user_id) values (?, ?, ?, ?, ?)

// Hibernate: insert into t_user3 (name, password, create_time, expire_time, user_id) values (?, ?, ?, ?, ?)

// Hibernate: update t_user3 set name = ?, Password = ?, Create_time = ?, Expire_time =? Where user_id =?

// Hibernate submits related operations in the order of save (insert), update, and delete

Tx. commit ();

} Catch (Exception e ){

E. printStackTrace ();

Tx. rollback ();

} Finally {

HibernateUtils. closeSession (session );

}

}

/**

* Test the assigned primary key generation policy.

*

*/

Public void testSave7 (){

Session session = null;

Transaction tx = null;

Try {

Session = HibernateUtils. getSession ();

Tx = session. beginTransaction ();

 

User3 user = new User3 ();

User. setId ("003 ");

User. setName ("Zhang San ");

Session. save (user );

User. setName ("Wang Wu ");

Session. update (user );

Session. flush ();

User3 user3 = new User3 ();

User3.setId ("004 ");

User3.setName ("Li Si ");

Session. save (user3 );

// Hibernate: insert into t_user3 (name, password, create_time, expire_time, user_id) values (?, ?, ?, ?, ?)

// Hibernate: update t_user3 set name = ?, Password = ?, Create_time = ?, Expire_time =? Where user_id =?

// Hibernate: insert into t_user3 (name, password, create_time, expire_time, user_id) values (?, ?, ?, ?, ?)

// Because flush is executed after session. udpate (user), the SQL statement before flush is not generated when the cache is cleared.

// The SQL statement will be executed as needed

Tx. commit ();

} Catch (Exception e ){

E. printStackTrace ();

Tx. rollback ();

} Finally {

HibernateUtils. closeSession (session );

}

}

}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.