Session save method and cache cleanup in hibernate

Source: Internet
Author: User

The SAVE () method of session converts a temporary object to a persistent object. For example:CodeSave a customer object:

 
Customer customer =NewCustomer (); customer. setid (NewLong (9 ));//The OID setting for the temporary customer object is invalid.Customer. setname ("Tom"); Session session=Sessionfactory. opensession (); transaction TX=Session. begintransaction (); Session. Save (customer); Session. Close ();

The SAVE () method of the session completes the following operations:

(1) Add the customer object to the cache to make it a persistent object.

(2) Select the identifier generator specified by the ing file to assign a unique oid to the persistence object. Customer. HBM. in the XML file, the <ID> element's <generator> sub-element specifies the identifier generator: (this configuration file is put together with the customer class, And the generator class has another value "native ")

 
<ID name = "ID" column = "ID"> <generator class = "increment"/> </ID>

AboveProgramAn error occurred while trying to set the oId for the temporary customer object through the setid () method. If there are no records in the MERs table at first, after the SAVE () method is executed, the ID of the customer object is 1. If you want the program to specify the oId for the customer object, you can call another overload method of SAVE:

 
Save (customer,NewLong (9 ));

The second parameter of the SAVE () method above shows the oId of the specified customer object. This form of SAVE () is not recommended, especially when the proxy primary key is used, the program should not specify the oId for the persistence object.

(3) execute an insert statement to assemble the current attribute value of the customer object into the insert statement:

 
Insert into MERs (ID, name,...) values (1, 'Tom ',......);

it is worth noting that the Save () method does not immediately execute the SQL insert statement . the SQL insert statement is executed only when the session clears the cache (transaction. Commit () when the transaction is committed. If after the SAVE () method, the attributes of the persistence object are modified, this causes the session to clear the cache, execute the SQL update statement. Although the following two sections of code can accomplish the same function, the code on the left executes only one SQL insert statement, the Code on the right executes an SQL insert statement and an SQL update statement. edge code reduces the number of database operations and provides better running performance .

Customer customer =NewCustomer (); customer =NewCustomer ();//First set the attributes of the customer object, and then save its session. Save (customer );Customer. setname ("Tom ");//Save the customer object and modify its attributes.Session. Save (customer); customer. setname ("Tom"); Transaction. Commit (); transaction. Commit (); // clear the cache at this time

Hibernate uses the persistence object oid to maintain its correspondence with database-related records. When the customer object is persistent, the program is not allowed to modify its OID at will,For example:

Customer customer =NewCustomer (); Session. Save (customer); customer. setid (NewLong (100 ));//Throw hibernateexceptionTransaction. Commit ();

The above code will cause the session to throw an exception when clearing the cache.

Note:No matter whether the Java object is in the temporary, persistent, or free state, the application should not modify its oid. Therefore, it is safer to set its setid () method to private when defining a persistent class and prohibit external programs from accessing this method.

The session save () method is used to persistTemporary object. In the ApplicationNoYou shouldPersistence object or free objectTo the SAVE () method. For example, the following code calls the SAVE () method of the session twice, and the customer that is passed to the SAVE () method for the second time is in the persistent state. This step is redundant:

Customer customer =NewCustomer (); Session. Save (customer); customer. setname ("Tom"); Session. Save (customer );//This step is redundant.Transaction. Commit ();

For example, run the following code to pass the free customer object to the SAVE () method of session2. session2 treats the object as a temporary object and inserts a customer record into the database again:

Customer customer = New  Customer (); customer. setname ( "Tom" ); Session session1 = Sessionfactory. opensession (); transaction tx1 =Session1.begintransaction (); session1.save (customer );  //  The ID of the customer object becomes 1.  Tx1.commit (); session1.close ();  //  The customer object becomes a free object. Session session2 = Sessionfactory. opensession (); transaction tx2 = Session2.begintransaction (); session2.save (cutomer );  //  In this case, the ID of the customer object is changed to 2.  Tx2.commit (); session2.close (); 

Although the above program code can run normally, there will be two records in the MERs table representing the same business entity, so they do not conform to the business logic.

Bytes ------------------------------------------------------------------------------------------------------

By default,SessionThe cache will be cleared at the following time points

1When the application callsNet. SF. hibernate. TransactionOfCommit ()Method,Commit ()Method: first clear the cache, and then look at the database to submit the transaction

2WhenSessionOfFind ()OrIterator ()If the attributes of the persistence object in the cache change, the cache is cleared first to ensure that the query results reflect the latest status of the persistence object.

3When the application explicitly callsSessionOfFlush ().

The setflushmode () method of the session is used to set the time point for clearing the cache. The flushmode class defines three different cleanup modes: flushmode. Auto, flushmode. Commit, and flushmode. Never. For example, the following code sets the Cleanup mode to flushmodo. Commit:

 
Session. setflushmode (flushmode. Commit );

Three cleanup Modes

 Cache cleanup Mode

Session Query Method

Session commit () method

Session flush () method

Flushmode. Auto Clear Clear Clear
Flushmode. Commit Do not clean Clear Clear
Flushmode. Never Do not clean Do not clean Do not clean

 

Flushmode. Auto is the default value, which is the preferred cleaning mode. It ensures data consistency throughout the transaction. If the transaction public contains the database query operation without modifying the database data, you can also choose flushmode. commit mode, which can avoid clearing the cache before executing the session query method to slightly improve the application performance.

In most cases, the application does not need to display the flush () method that calls the session. The flush () method is applicable to the following scenarios:

(1) Inserting, deleting, or updating a persistent object will trigger a trigger in the database. When a record is added to the pseudo-targeted MERs table, a database trigger is triggered. In the application, a customer object is saved through the SAVE () method of the session, and the application then calls the flush () method of the session () method:

 
Session. Save (customer); Session. Flush ();

The session flush () method immediately executes the insert statement, which then triggers related triggers.

(2) hybrid use of hibernate APIs and JDBC APIs in applications.

(3) The JDBC driver is not robust, so hibernate cannot work properly in the automatic cache cleaning mode.

 We know that if we put new data in the cache, our computer will surely crash in memory. Therefore, it is necessary to clear the necessary cache.
The following describes several methods:
1,

For(IntI = 0; I <1000; I ++) {Order=NewOrder (); Order. setid (); Session. Save (order );If(I % 100 = 0) {Session. Flush (); Session. Clear ();}}

2,

 
For(IntI = 0; I <1000; I ++) {Order=NewOrder (); Order. setid (); Session. Save (order); Session. evict ();//Clear session cacheSessionfactory. evict ();//Clear level 2 Cache}

Note:The primary cache is valid only in the same session, and the secondary cache is global.

 
The first-level cache is the session-level cache. When a session performs a query operation, it places the result of this operation in the first-level cache, if this session (must be the same session) performs the same operation in a short period of time, Hibernate directly retrieves the data from the first-level cache instead of connecting to the database.
The second-level cache is the sessionfactory-level cache. As the name suggests, the query results are cached in the second-level cache during queries. If a session created by the same sessionfactory performs the same operation, hibernate will get the results from the second-level cache instead of connecting to the database. (
Hibernate cache includes session cache and sessionfactory cache. sessionfactory cache can be divided into two types: built-in cache and external cache. The session cache is built-in and cannot be detached. It is also called the first-level cache of hibernate. The built-in cache of sessionfactory is similar to the session cache implementation method. The former is the data contained in some collection attributes of the sessionfactory object, and the latter is the data contained in some collection attributes of the session. The built-in cache of sessionfactory stores the ing metadata and predefined SQL statements. The ing metadata is a copy of the data in the ing file, the predefined SQL statement is derived from the ing metadata in the hibernate initialization phase. The built-in cache of sessionfactory isRead-OnlyApplications cannot modify the ing metadata and predefined SQL statements in the cache.Sessionfactory does not need to synchronize built-in cache and ing files. The external cache of sessionfactory is a configurable plug-in. By default, sessionfactory does not enable this plug-in. External cache data is a copy of database data, and external cache media can be memory or hard disk. The external cache of sessionfactory is also called the second-level cache of hibernate.
 
)

Evict () method
This method is different from the previous method. It can only be used to clear a single object.

Clear () method
We can create a property tag under the session-factory tag. The name attribute isHibernate. JDBC. batch_size. The value is the number we want to set. For example, if it is 100, the session is called when we execute the flush () operation to send an SQL statement. clear () method to clear the cache.

 

 

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.