Java programmers go from stupid birds to cainiao () to talk about the hibernate (13) session cache mechanism and three object states

Source: Internet
Author: User


Hibernate provides us with the main interface for manipulating databases. session is one of them. It provides basic addition, deletion, modification, and query methods. it also has a caching mechanism that updates the database according to the changes in the persistence object attributes in the cache at a certain time point, which is the cache Cleaning Process of the session. in hibernate, objects are divided into three states: temporary, persistent, and free. if we want an object in Java to always exist, there must be a variable that always references this object. when this variable is missing. the object is recycled by JVM. this blog will show you the session cache mechanism, that is, the hibernate level-1 cache, and the details of the three object states of hibernate.

When the session save () method persists a customer object, the customer object is added to the session cache, even if the reference variable in the application does not reference the customer object, as long as the session cache is not cleared, the customer object is still in the lifecycle. When the load () method of the session tries to load a customer object from the database, the session first checks whether the customer object already exists in the cache. If so, it does not need to be retrieved from the database. This greatly improves the time efficiency of hibernate queries. The session cache will expire only when the transaction is committed and the session is closed.

Here we will use a piece of code to understand the session cache:

Tx = session. begintransaction (); customer C1 = new customer ("zhangsan", new hashset (); // The customer object is persisted and added to the session cache. save (C1); long id = c1.getid (); // The C1 variable no longer references the customer object C1 = NULL; // read the customer object from the session cache, make the C2 variable reference the customer object customer C2 = (customer) session. load (customer. class, ID); Tx. commit (); // close the session and clear the cache session. close (); // access the customer object system. out. println (c2.getname (); // The C2 variable no longer references the customer Object. the lifecycle of the customer object ends. C2 = NULL;

When the session calls save to save an object, the object is loaded into the session cache. In fact, the details of calling the Save method are ignored, that is, the SAVE method has a return value, which returns data of the seriaseble interface type. We know that all the packaging types like basic data have implemented this interface, in fact, this return value can be understood as the ID of the object to be saved. We can use this return value in many cases, which is a point of attention. When an object is saved to the cache, we can call the GETID method of the object to obtain its ID. In the above example, we can see that although C1 is reset to null, there is still a variable in the session cache pointing to this object, so this object will not be recycled by the garbage collector, when we use the ID of this object to use the load query, we still go to the session cache to find the object and return the object. After the session is closed. Cache cleared.

Let's look at an example to see another difference between get and load:

tx = session.beginTransaction(); Customer c1=(Customer)session.load(Customer.class,new Long(1)); Customer c2=(Customer)session.load(Customer.class,new Long(1)); System.out.println(c1==c2); // true or false ?? tx.commit(); session.close(); 

Obviously, the final result of this example is true, because they get the same instance. Let's analyze it in detail. When we run this code, careful kids shoes should find that when using load to query objects, no SQL statements are generated. Why? Since the query results have been found, why haven't the SQL statements been generated. This is the second difference between the load and get methods. The load method is actually a proxy object of the object obtained during query, when we use the queried object, it will go to the database for query. As shown above, if we call the c1.getname method, an SQL statement will be printed, at this time, he really went to the database to query, and the get method, he will go to the database to query when executing the get method, generate SQL statements

Role of session cache

(1) reduce the frequency of accessing the database. The speed at which the application reads persistent objects from the memory is much faster than that of querying data in the database. Therefore, the session cache can improve the data access performance.

(2) ensure that the objects in the cache are synchronized with relevant records in the database. When the status of the persistence object in the cache changes, the session does not immediately execute related SQL statements, which allows the session to merge several related SQL statements into one SQL statement, in order to reduce the number of visits to the database, thus improving the performance of the application.

Session cleanup Cache

Cache cleanup refers to synchronously updating the database based on changes in the state of the objects in the cache. Let's take a look at the code below: the following code modifies the customer's name attribute twice:

tx = session.beginTransaction(); Customer customer=(Customer)session.load(Customer.class, new Long(1)); customer.setName("Jack"); customer.setName("Mike"); tx.commit(); 

When the session clears the cache, you only need to execute an update statement:

Update MERs set name = 'Mike '...... Where id = 1;

In fact, the first call to setname is meaningless and can be omitted.

When will the session cache be cleared? Let's take a look:

The session clears the cache at the following time points:

1. When the application calls the Commit () method of org. hibernate. transaction, the Commit () method first clears the cache and then submits transactions to the database.

2. when the application explicitly calls the flush () method of the session, in fact, this method is rarely used, because we usually clean up the cache and commit data changes after a transaction is completed, in this way, you can directly commit the transaction.

Three States of Java objects in hibernate:

1. temporary status (transient): It was just created with the new statement and has not been persisted yet, and is not in the session cache. A Java object in the temporary state is called a temporary object.

2. Persistent: it has been persisted and added to the session cache. A persistent Java object is called a persistent object.

3. Detached: it has been persisted but is no longer in the session cache. A Java object in the free state is called a free object.

The difference between the Persistence State and the temporary state is:

1. When the object is in persistent state, it has already been dealing with the database, and there is a record of the object in the database.

2. Objects in the persistent state exist in the session cache.

3. Objects in the persistent State have their own oid.

Objects in the Free State are different from objects in the persistent state. Objects in the Free State are no longer in the session cache, and no records of this object exist in the database, but he still has his own oid.

Object State Conversion

Let's take a look at this state transition diagram. First, an object is in a temporary state after it is new, and then the Save or saveorupdate method is called to convert the object to a persistent state, the saveorupdate method here is actually a lazy method. All the Save methods we used previously can be changed to this method, this method first checks the status of the object before saving the data. If it is in the temporary status, it is saved. If it is in the free status, it is updated. The Persistence State can be converted to the Free State when the session is closed or the cache is cleared, or the evict method is called. This method is to forcibly clear the object from the session cache. The update method can be called when the Free State is changed to the persistent state. In fact, the main function of the update method is to replace the object from the Free State with the persistent state, because this method is not used for general updates.

Let's take a look at the status transition process for a specific instance:


This figure requires a careful understanding of the process of object lifecycle and object state conversion.

Next we will use an example to illustrate how the update method of the session changes an object in the Free State to persistent:

Customer customer = new customer (); customer. setname ("Tom"); Session session1 = sessionfactory. opensession (); transaction tx1 = session1.begintransaction (); session1.save (customer); tx1.commit (); session1.close (); // The customer object becomes the free object session session2 = sessionfactory. opensession (); transaction tx2 = session2.begintransaction (); customer. setname ("zhangsan") // modify the attributes of the customer object session2.update (customer); customer before associating with session2. setname ("Lisi"); // after being associated with session2, modify the attributes of the customer object tx2.commit (); session2.close ();

When session1 saves the object and closes the transaction, the object changes to the Free State. At this time, we are opening a session and using the update method to associate the object with the session, then modify its attributes. After the transaction is committed, objects in the Free State can be modified and saved to the database. Although the attributes of the objects are modified twice, only one SQL statement is sent, because update sends an SQL statement only when the transaction is committed when modifying object data. So only the last modification information works.

Summarize the update () method of the session to complete the following operations:

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

(2) execute an update statement. It is worth noting that,The session will only execute the update statement when clearing the cache.And the current property value of the customer object will be assembled into the update statement during execution. Therefore, even if the attributes of the customer object are modified multiple times in the program, only one update statement is executed when the cache is cleared.

The process of transferring temporary objects and advantageous objects between the web application Client layer and the business logic layer:

Session second-level cache

Hibernate provides two levels of cache. The first level of cache is the session cache. Because the lifecycle of a Session Object usually corresponds to a database transaction or an application transaction, its cache is the cache of the transaction scope. The first-level cache is required and cannot be detached. In the first cache, each instance of the persistence class has a unique oid. The second-level cache is a pluggable cache plug-in managed by sessionfactory. Because the life cycle of the sessionfactory object corresponds to the entire process of the application, the second-level cache is the process-range cache. This cache stores the object's bulk data. The second-level cache is optional. You can configure the second-level cache at the granularity of each class or set.

Hibernate second-level cache structure


For details about the hibernate second-level cache, we will introduce it in detail in a later blog. Here we will just give a brief introduction. For details, please wait for future articles ....

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.