Three types of data persistence states and caching mechanisms in the--hibernate of Java three frameworks

Source: Internet
Author: User

Three states in Hibernate

transient state: the object you just created also no data is persisted by the session, the object does not exist in the cache, and the data in the database does not correspond to the instantaneous state at this time there is no OID.    

  Persistent State: The object is persisted by session, the data in the cache exists in the persistent state and the data in the database exists for the persistent state.

  Free State: When the session is closed, the object data does not exist in the cache and there is data for the object in the database and the OID is Free State.

Note:OID To be able to find the desired object in the system, we need to assign a unique representation number to each object. In relational databases we call them keywords, and in object terms, they are called object identifiers .

(Object identifier-oid). usually the OID is represented internally by one or more large integers, while in the application a complete class is provided to provide the fetch and operation for the other classes.

  Hibernate Data Status Graph:

    

It is important to note that:

When the temporary state of an object becomes persisted. When the object is persisted, it is always in the Session's cache, and any operation on it will be synchronized to the database when the transaction commits, so it makes no sense to call the Save () or Update () method on an already persisted object.   

New strudnet (); Stu.setcarid ("200234567"); Stu.setid ("the "); // Open Session, turn on transaction // persisting the Stu object Session.save (Stu); Stu.setcardid ("20076548"); // persist the Stu object again // Invalid  //  Invalid //  COMMIT TRANSACTION, close Session

Hibernate caching mechanism

What is a cache?

  Caching is between an application and a physical data source, and it is designed to reduce the frequency of application access to physical data sources, thereby improving the performance of the application. The data in the cache is a copy of the data in the physical data source, the application reads and writes data from the cache at run time, and at a particular moment or event synchronizes the cache and the data from the physical data source.  

What are the benefits of caching?

  The benefit of caching is to reduce the number of database accesses, improve application performance, and reduce the time to read and write data.

When is it appropriate to use caching?

  programs often use some unchanging data content, from the database will not go to often modify it and often need to be used to consider doing a cache, read from the cache after reading, and do not have to query the database every time. because the speed of the hard disk is much slower than the memory speed. in order to improve the performance of the program, the cache will appear to solve this problem

Cache in Hibernate

  the caches in hibernate include the first level cache (Session cache), the level two cache (Sessionfactory cache) , and the query cache .

    

    First level cache (session cache)

Because the life cycle of a Session object usually corresponds to a database transaction or an application transaction, its cache is a transaction-scoped cache. Session-level caching is required, is not allowed, and in fact cannot be removed. In a session-level cache, each instance of a persisted class has a unique OID.

When the application invokes the session's Save (), update (), Savaeorupdate (), get (), or load (), and the list (), iterate (), or filter () method that invokes the query interface, If the corresponding object does not exist in the session cache, hibernate will add the object to the first level cache.

When you clean up the cache, hibernate synchronizes updates to the database based on the state of the objects in the cache.

Session provides two ways for the application to manage the cache: evict (object obj): Clears the persisted object specified by the parameter from the cache. Clear (): Empties all persisted objects in the cache.

     Public Static void Testonelevecache () {        session session=hibernateutil.getsession ();         // gets the Persisted object dept        Dept d1= (Dept) session.get (Dept.class, ten);         // gets the persisted object again dept        Dept d2= (Dept) session.get (Dept.class, ten);            Session.close ();    }

The Dept object is obtained by default by the Get () method of the session to save the Dept object to the first level cache (session cache) when the second fetch, the corresponding object is queried from the first level cache ( If the session cannot be emptied or closed, the primary cache will be emptied or destroyed . If the corresponding object exists in the first level cache, it will not be queried in the database, so the query code that executes the query only once is as follows:

Hibernate:     select        dept0_. DEPTNO as deptno0_0_,        dept0_. Dname as dname0_0_,        dept0_. LOC as loc0_0_     from        SCOTT. DEPT dept0_     where        dept0_. DEPTNO=?

  How do I clear the first level cache?

  Through Session.clear ();//Clear All caches

Session.evict ();//clear the specified cache

     Public Static voidTestonelevecache () {Session session=hibernateutil.getsession (); Sessionfactory SF=hibernateutil.getsessionfactory (); //gets the persisted object deptDept d1= (Dept) session.get (Dept.class, 10); Session.clear ();//Clear All cachesSession.evict (D1);//clear the specified cache//gets the persisted object again deptDept d2= (Dept) session.get (Dept.class, 10);    Session.close (); }

Using Session.evict (Object obj) deletes the specified bean, so you execute two SQL statements when you query a bean that you delete a level two cache

Using Session.clear () cleanup, you will find that two SQL statements have been executed:

Hibernate:     select        dept0_. DEPTNO as deptno0_0_,        dept0_. Dname as dname0_0_,        dept0_. LOC as loc0_0_     from        SCOTT. DEPT dept0_     where        dept0_. DEPTNO=? Hibernate:     select        dept0_. DEPTNO as deptno0_0_,        dept0_. Dname as dname0_0_,        dept0_. LOC as loc0_0_     from        SCOTT. DEPT dept0_     where        dept0_. DEPTNO=?

  

Level Two cache (Sessionfactory cache)

Because the life cycle of the Sessionfactory object corresponds to the entire process of the application, hibernate level Two caches are process-wide or cluster-wide caches, and concurrency problems may occur, so appropriate concurrent access policies are required. This policy provides a transaction isolation level for cached data.

The save, update, saveorupdate, load, get, list, query, criteria methods populate the level two cache

Get, load, iterate will fetch data from the level two cache Session.save (user)

If the user primary key is generated using "native", the level two cache is not placed.

The second-level cache is optional and is a configurable plug-in, which is not enabled by default under Sessionfactory. Hibernate provides the Org.hibernate.cache.CacheProvider interface, which acts as an adapter between the cache plug-in and hibernate.

The general process for Hibernate's level two cache strategy is as follows:
1) When a condition is queried, always issue a SELECT * FROM table_name where .... (select all fields) such SQL statements query the database and get all the data objects at once.
2) Put all the obtained data objects into the second level cache based on the ID.
3) When hibernate accesses the data object according to the ID, it is first checked from the session cache, and if the level two cache is configured, it is checked from the level two cache, and the database is not found, and the result is placed in the cache by ID.
4) Update the cache while deleting, updating, and adding data.
Hibernate's level two cache policy, which is a cache policy for ID queries, has no effect on conditional queries. To do this, hibernate provides a query cache for conditional queries.

Configure Level Two cache (Sessionfactory cache):

  Configure the following code in Hibernate.cfg.xml

    <!--turn on level two cache-    <property name= "Hibernate.cache.use_second_level_cache" >true</ Property>    <!--to hibernate specify implementation class for two-level caching--    <property name= "Hibernate.cache.provider_class" > Org.hibernate.cache.ehcacheprovider</property>

  There are two ways to indicate which classes need to be placed in a level two cache, where objects that require long-term use are required to be placed in a level two cache into a two-level cache:

1. Configuring in Hibernate.cfg.xml

<classclass// does not allow updating objects in the cache <class= "entity. Petinfo "usage=" Read-write "/>  // allow updating of objects in cache

    2. Configure in the BEAN.HBM file

class name= "Com.bdqn.entity.Dept" table= "Dept" schema= "SCOTT"  >        <cache usage= "read-only"/>// put this class in level two cache        <id name= "Deptno" type= " Java.lang.Integer ">            <column name=" DEPTNO "precision=" 2 "scale=" 0 "/>            class=" Assigned " ></generator>        </id>        <property name= "dname" type= "java.lang.String" >            < Column Name= "Dname" length= "+"/>        </property>    </class>

  

  You can set the maximum number of caches, whether they are permanent, time, etc. in the Ehcache.xml configuration file

<defaultcache        maxelementsinmemory= "10000"        eternal= "false"         Timetoidleseconds= "        timetoliveseconds" = "        overflowtodisk" = "true"        / >

How do I clear level two cache?

  You need to use Sessionfactory to manage level two cache code as follows:

Sessionfactory.evict (Entity.class);//Clear All Entitysessionfactory.evict (Entity.class, id);//clears the specified entityFor example://Manage level Two cache with SessionfacotrySessionfactory Factory=hibernateutils.getsessionfactory ();//evict () clears the student object with ID 1 from the two-level cache.factory.evict (Student.class, 1); //evict () clears all level two caches.factory.evict (Student.class);

what data is suitable for storage in the second level cache?
1) rarely modified data
2) data that is not very important, allowing occasional concurrent data to occur
3) data that will not be accessed concurrently
4) Constant data
not suitable for storing data in a second level cache?
1) Frequently modified data
2) never allow concurrent access to data, such as financial data, is never allowed to appear concurrency
3) data that is shared with other apps.

  Query cache

Hibernate's query cache is primarily a cache of common attribute result sets, whereas the result set for an entity object caches only the ID.

In the case of a first-level cache, where the two-level cache and the query cache are open, the query operation is as follows:

Query the normal properties, will go to the query cache first, if not, query the database, query entity, the query cache first to take the ID, if there is, according to the ID to cache (level/level two) of the entity, if the cache does not take the entity, then query the database.

In the Hibernate.cfg.xml configuration file, open the query cache

<!--whether the query cache is turned on, true to turn on query caching, false to close the query cache--><property name= "Cache.use_query_cache" >true</ Property>

Query caching also needs to be enabled in the program after the query cache is turned on

 Public Static void Testquerycache () {        session session=hibernateutil.getsession ();        String hql= "from Emp as E";        Query Query=session.createquery (HQL);        Query.setcacheable (true); // Enable query caching (level two cache)        List<emp> emplist=query.list ();        Session.close ();}        

The query cache is based on a two-level caching mechanism if the two-level cache code is not turned on according to the Bean's property query as follows:

Session =hibernateutils.getsession (); T=session.begintransaction (); Query Query= Session.createquery ("Select S.name from Student S"); //Enable query cachingQuery.setcacheable (true); List<String> names =query.list ();  for(Iterator<string> it =names.iterator (); It.hasnext ();) {String name=It.next ();       SYSTEM.OUT.PRINTLN (name); } System.out.println ("================================"); Query= Session.createquery ("Select S.name from Student S"); //Enable query cachingQuery.setcacheable (true); //No query statement was issued because the query cache used hereNames =query.list ();  for(Iterator<string> it =names.iterator (); It.hasnext ();) {String name=It.next ();       SYSTEM.OUT.PRINTLN (name); } t.commit (); 

Three types of data persistence states and caching mechanisms in the--hibernate of Java three frameworks

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.