Beginner easy to get started SSH-hibernate03 three states and cache,

Source: Internet
Author: User

Beginner easy to get started SSH-hibernate03 three states and cache,

This chapter focuses on the three major statuses and caches of hibernate. First, let's look at the three major statuses:

For example, the three statuses are temporary, Persistent, and Detached ). How can we explain the three states?

Student stu = new Student ("Student 1", "male", "Changsha", 20 );

The code snippet above,A new student object. This object exists in the memory, but does not exist in the database or session cache. This is a temporary state..

Student stu = new Student ("Student 1", "male", "Changsha", 20); session. saveOrUpdate (stu );

Transaction. commit ();

 The new object is added to the session cache, and the underlying SQL statement operation object is added to the database, that is, the object is in the persistent state.

        session.close();            sessionfactory.close();

After closing the session object, the student object still exists in the database,But does not existSession, that is, the session object is detached.

 

Next let's look at the cache:

The cache is between the physical data source and the application. It copies a copy of the data in the database to a container temporarily placed in the memory. Its function is to reduce the number of times the application accesses the physical data source, this improves the Running Performance of applications. When Hibernate reads data, It queries the data in the corresponding cache based on the cache mechanism. If the required data is found in the cache (we call this "cache "), the hit data is directly used as the result to avoid performance loss when a large number of SQL statements are sent to the database for query.

Hibernate cache is divided into Level 1 cache and level 2 Cache. Level 1 cache is our common session, and level 2 cache is SessionFactory.

The Session cannot be uninstalled, and the Session cache is the cache of the transaction scope (the lifecycle of the Session Object usually corresponds to a database transaction or an application transaction ).
In the level-1 cache, each instance of the persistence class has a unique OID.

Because the life cycle of the SessionFactory object corresponds to the whole process of the application, The Hibernate second-level cache is a cache of process scope or cluster scope, which may cause concurrency problems, therefore, an appropriate concurrent access policy is required, which provides a transaction isolation level for cached data.
The second-level cache is optional and is a configurable plug-in. By default, SessionFactory does not enable this plug-in.
Hibernate provides the org. hibernate. cache. CacheProvider interface, which acts as an adapter between the cache plug-in and Hibernate.

Generally, data with the following features is put into the second-level cache:

● Rarely modified data.

● Not very important data, allowing occasional concurrent data.

● Data that will not be accessed concurrently.

● Reference data.

Data with the following features is not suitable for the second-level cache:

● Frequently modified data.

● No concurrency is allowed for financial data.

● Data shared with other applications.

Configure a second-level cache.

First, import the ehcache package and the hibernate-ehcache package (corresponding to the hibernate version). Since it is a maven project, introduce dependencies in pom. xml.

<!--hibernate-ehcache -->        <dependency>            <groupId>org.hibernate</groupId>            <artifactId>hibernate-ehcache</artifactId>            <version>5.2.10.Final</version>        </dependency>        <!--net.sf.ehcache/ehcache -->        <dependency>            <groupId>net.sf.ehcache</groupId>            <artifactId>ehcache</artifactId>            <version>2.10.4</version>        </dependency>

Configure in hibernate. cfg. xml.

<! -- Enable Level 2 cache --> <property name = "cache. use_second_level_cache"> true </property> <! -- Enable second-level cache query --> <property name = "cache. use_query_cache"> </property> <! -- Hibernate4.0 and later settings factory cache tools --> <property name = "hibernate. cache. region. factory_class"> org. hibernate. cache. ehcache. EhCacheRegionFactory </property> <! -- Location of the configuration file for level-2 cache ehcache --> <property name = "hibernate. cache. provider_configuration_file_resource_path"> ehcache. xml </property> <! -- Ing file --> <mapping resource = "com/entity/Student. hbm. xml"/> <! -- The class to be cached --> <class-cache usage = "read-only" class = "com. entity. Student"/>

Put the ehcache. xml file at the same level as hibernate. cfg. xml. The elements in ehcache. xml can be found directly in the following path, and do not need to be written by yourself. Project-> Java Resources-> Libraries-> Maven Dependencies-> ehcache-2.10.4.jar-> ehcache-failsafe.xml

Open it, select copy, and change the path in the <diskStore path = "java. io. tmpdir"/> node to your own defined path. Finally, test the second-level cache.

@ Test public void test () {// obtain Configuration information configuration = new Configuration (). configure (); // obtain the Session factory SessionFactory factory = configuration. buildSessionFactory (); // obtain Session session = factory. openSession (); Session session1 = factory. openSession (); // enable Transaction transaction = session. beginTransaction (); // obtain the object based on the primary key (query a single record) Student st = session. get (Student. class, 1); System. out. println (st); // List of second-level caches <Student> ls = session1.createQuery ("from Student "). setCacheable (true ). list (); for (Student s: ls) {System. out. println (s);} // submit transaction // transaction. commit (); // close the seeion session. close (); // close SessionFactory factory. close ();}

 

I am not very familiar with caching!
This chapter ends.

 

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.