Hibernate three status, cache, and update updates issues

Source: Internet
Author: User
Tags sesion

I. Three states of objects in Hibernate 1. Transient status (transient)

When we generate an entity object from the Java New keyword, the entity object is in a free State, and the object is simply getting a chunk of memory through the JVM and not being saved into the database through the Save () method of the Session object. So it is not included in Hibernate's cache management, which means that the object is now free to roam outside of hibernate cache management. So we can see that the most important feature of a free object is that there is no record in the database that corresponds to it.

Transient state features:

I: not associated with the Session instance;

II: There are no records associated with instantaneous objects in the database

2. Persistent State (persistent)

The persisted object is the entity object that has been saved into the database, and the entity object is now in Hibernate cache management. This is any modification to the entity object that will be synchronized to the database when the cache is cleaned up.

Persistent State features:

I:session Instance Association

II: There are records associated with persistent objects in the database

3. Free State (detached)

When a persistent object, out of hibernation cache management, it is in a free State, free objects and free objects The biggest difference is that the free object in the database may also have a corresponding record, but now this free object out of Hibernate cache management, The free object does not appear in the database with its corresponding data record.

Characteristics of Off-pipe objects:

I: Essentially the same as instantaneous objects

II: Just more than love instantaneous object a database record identity value ID.

The state diagram of three states is converted as follows:

two. Hibernate performing an update operation accesses the database several times

First you need to know how Hibernate performs the update operation, and how does hibernate update automatically update?

(1). Hibernate performs a select operation in the database to find the primary key for the object that is currently being update, similar to the following:

Select ID from table where id=xxx;

(2). Perform an update operation

I: If the ID is found, it means that the object is a persisted object, and hibernate automatically performs an update operation to synchronize the object in the database if certain properties of the object change.

II: If hibernate does not find the ID, it means that the object is a free object, and hibernate inserts the action on its own.

Based on these, you can understand that the ID of the object to update does not exist in the database, or change the ID of the object, which is done by insert instead of update.

three. Hibernate in first-level cache and level two cache 1. First-level cache two-level cache concept resolution

(1) A cache is the session level cache, a session to do a query operation, it will put the results of this operation in a first-level cache, if a short period of time this

Session (must be the same session) and do the same operation, then hibernate directly from the first cache to take, and will not go to the database, fetch data;

(2) Level two cache is the sessionfactory level of cache, as the name implies, query results will be cached to the level two cache, if the same sessionfactory

When a session is created that performs the same action, Hibernate takes the result from the level two cache and no longer connects to the database;

(3) Hibernate provides a level two cache, and the first level of cache is session-level caching, which is a transaction-scoped cache. This level of caching is managed by hibernate

, generally without intervention; the second level of caching is the sessionfactory level of caching, which is a process-wide or cluster-wide cache. This level of other slow

Storage can be configured and changed, and can be dynamically loaded and unloaded. Hibernate also provides a query cache for query results, which relies on the second level cache;

2. First-level cache comparison of level two caches

(1) First-level cache second-level cache holds data in the form of a wide range of data caches that are associated with persisted object objects in the bulk of a transaction scope, each transaction has a separate first level

Cache process scope or cluster scope, cache is shared by all transactions within the same process or cluster for concurrent access policies because each transaction has a separate first-level cache, no

Concurrency issues occur without the need to provide concurrent access policies because multiple transactions access the same data in the second-level cache at the same time, an appropriate concurrency access policy must be provided to protect

Data expiration policy for a specific transaction isolation level does not provide a data expiration policy.

(2) objects in the first-level cache never expire unless the application explicitly empties the cache or

Clearing a specific object must provide a data expiration policy, such as the maximum number of objects in the memory-based cache, allowing the object to be in the cache for the longest time, and allowing the object to

The maximum idle time in the cache physical storage media memory and hard disk.

(3) The bulk data of the object is first stored in the memory-based cache, when the number of objects in memory reaches the number

When the upper limit is specified in the expiration policy, the remaining objects are written to the hard disk-based cache.

(4) The cached software implementation includes the cache in the implementation of the hibernate session.

The implementation is provided by a third party, and hibernate only provides a cache adapter (Cacheprovider). Used to integrate specific cache plugins into hibernate.

(5) How to enable caching

Hibernate enables first-level caching as long as the application performs the operations of saving, updating, deleting, loading, and querying database data through the session interface, and the database

Data is copied to the cache in the form of objects, for bulk updates and bulk Delete operations, if you do not want to enable first level caching, you can bypass the hibernate API and directly

Use the JDBC API to perform a finger operation.

(6) A user can configure a second-level cache on the granularity of a single collection of classes or classes. If an instance of a class is read frequently but is seldom modified, it

You might consider using a second-level cache.

(7) Only a second level cache is configured for a class or collection, and Hibernate adds its instance to the second level cache at run time.

How the user manages the cache the first-level cache of physical media is memory, and due to limited memory capacity, the number of loaded objects must be limited by appropriate retrieval policies and retrieval methods.

The Evit () method of the session can explicitly empty the cache for specific objects, but this method is not recommended. The second-level cache of physical media can be memory and hard disk, so the second

Level caches can hold large amounts of data, and the Maxelementsinmemory property value of the data expiration policy can control the number of objects in memory.

(8) The management of the second level cache mainly includes two aspects: Select the persistence class that needs to use the second level cache, set the appropriate concurrency access policy: Select the cache adapter, set the appropriate data expiration policy.

3. Management of first-level caches

(1) When the application invokes the session's Save (), update (), Savaeorupdate (), get () or load (), and the list (), iterate (), or

Filter () method, Hibernate will add the object to the first level cache if the corresponding object does not exist in the session 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 to manage caching for your application: evict (Object obj)

: Clears the persisted object specified by the parameter from the cache. Clear (): Empties all persisted objects in the cache.

(2) Save, update, saveorupdate, load, list, iterate, lock will store data to the first level cache;

1 Save case: 2     //Add a Student 3             Student student=new Student (); 4             student.setname ("Little East"); 5  6             s.save (Student );//Put in a  cache             of 7 8///I'll check right away 9             Student stu2= (Student) s.get (Student.class, Student.getid ());//select10             System.out.println ("You just joined the student name is" +stu2.getname ());

(3) What operation will fetch data from the first level cache: Get, load, list

Get/load will first be taken from the primary cache, if not. There are different operations [get will immediately send a request to the database, and load will return a proxy object until the user actually uses the data to send a request to the database;

Check Student number 45th

1 Save case: 2     //Add a Student 3             Student student=new Student (); 4             student.setname ("Little East"); 5  6             s.save (Student );//Put in a  cache             of 7 8///I'll check right away 9             Student stu2= (Student) s.get (Student.class, Student.getid ());//select10             System.out.println ("You just joined the student name is" +stu2.getname ());

From the above case, we see that query.list () Query.uniueresut () does not take data from the first level! However, query.list or Query.uniquerestu () will store the data in the first level.

Attention:

① first-level cache does not need to be configured, it can be used, it does not have a protection mechanism, so we programmers to consider this problem, we can with evict or clear to remove the session cache objects. Evict is clearing an object, clear is clearing all sesion cache objects

The life cycle of an object in the ②session cache, which is automatically destroyed when the session is closed.

③ we use HashMap to simulate a session cache, deepening the cache.

management of 4.Hibernate level two cache the general process for the I. Hibernate level Two cache policy 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 level Two cache policy is a cache policy for ID queries and is not useful for conditional queries. To do this, Hibernate provides query Cache for conditional queries.

5) A level two cache object may be placed in memory, or it may be placed on disk.

Ii. 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) Reference data, refers to the supply of constant data reference, its limited number of instances, its instances will be referenced by many other instances of the class, the instance is rarely or never modified.

III. Data that is not suitable for storage in the second level cache?

1) Frequently modified data

2) financial data, never allow concurrency

3) data that is shared with other apps.

Iv. Common Cache plug-in hibernater level two cache is a plugin, here are a few common cache plugins:

Ehcache: As a process-wide cache, the physical media that holds the data can be either memory or hard disk, which provides support for Hibernate's query caching.

Oscache: As a process-wide cache, the physical media that holds the data can be either memory or hard disk, providing a rich cache data expiration policy for hibernate queries

The cache provides support.

Swarmcache: Can be used as a cluster-wide cache but does not support Hibernate's query cache.

JBossCache: Can be used as a cluster-wide cache, supports transactional concurrency access policies, and provides support for hibernate query caching.

v. Main steps for configuring Hibernate level two cache:

1) Select the persistence class that requires a level two cache, and set its concurrent access policy for the named cache. This is the most serious step to consider.

2) Select the appropriate cache plug-in, and then edit the plugin's configuration file.

1 <property name= "Hbm2ddl.auto" >update</property> 2     <!--start Level two cache-3     <property name= " Cache.use_second_level_cache ">true</property> 4     <!--Specify which level of two cache to use--5     <property name=" Cache.provider_class ">org.hibernate.cache.OSCacheProvider</property> 6     <mapping resource=" com/ Hsp/domain/department.hbm.xml "/> 7     <mapping resource=" Com/hsp/domain/student.hbm.xml "/> 8     <!- -Specify which domain enables level two cache  9     special description level Two cache policy:     1. Read-only11     2. Read-write12     3. Nonstrict-read-write13     4. Transcational14     -->15     <class-cache usage= "Read-write"/>

3) The Oscache.properties file can be placed in the SRC directory, so you can specify the capacity size of the object into the level two cache. Default 1000

VI. Using level Two caching:
 1//TODO auto-generated Method Stub 2//By getting a sesion, let Hibernate framework run (config-> load hibernate.cfg.xml) 3 Se Ssion S=null; 4 Transaction Tx=null; 5 6 try {7///We use the basic template to explain. 8 S=hibernateutil.opensession (); 9 Tx=s.begintrans        Action (); 10 11//Query number 45th students Student stu1= (Student) S.get (Student.class, $);//45-> level cache             System.out.println (Stu1.getname ()); Tx.commit (); (Exception e) {19} E.printstacktrace (); if (tx!=null) {tx.rollback ();}23}fi         nally{24 if (s!=null && s.isopen ()) {s.close (); 27}28}29 30             System.out.println ("*********************************"); try {32///We use the basic template to explain. 33 S=hibernateutil.opensession (); Tx=s.begintransaction (); 35 36//Enquiry 45th Student 37 38 Student stu1= (Student) s.get (Student.class, 45);    System.out.println (Stu1.getname ()); Student stu3= (Student) s.get (Student.class, 46);             System.out.println (Stu3.getname ()); Tx.commit (); the catch (Exception e) {46 E.printstacktrace (); if (tx!=null) {tx.rollback ();}50}fi         nally{51 if (s!=null && s.isopen ()) {s.close (); 54}55}56 57 Complete a statistic that counts the information in the Sessfactory58//sessionfactory object. Statistics statistics= hibernateutil.getsessionf Actory (). Getstatistics (); System.out.println (statistics); System.out.println ("Put" +statistics.getsecond Levelcacheputcount ()); System.out.println ("Hit" +statistics.getsecondlevelcachehitcount ()); SYSTEM.OUT.P Rintln ("Miss" +statistics.getsecondlevelcachemisscount ());

After configuring the level two cache, please be aware that you can check your configuration hit rate is not high by Statistics

Hibernate three status, cache, and update updates issues

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.