Getting Started with Hibernate (iv)

Source: Internet
Author: User

One hibernate cache

The cache is between the application and the database, the data in the database is replicated to the cache, it is to reduce the application to the database access, access to the database first from the cache, improve the performance of the program. The hibernate cache is divided into a primary cache and a level two cache:

First-level cache: Cache scope is shared in the session, the lifecycle of the cache depends on the session life cycle, the session closed, the cache is closed, the first cache is hibernate built-in, not removable.

Second-level cache: The cache scope is shared in Sessionfactory, using third-party plug-ins, pluggable, the lifecycle of the cache depends on the life cycle of the application, and when the application ends, the cache ends the lifecycle.

Level 21 Cache

When the following actions occur, the data is put into the cache:

1. Save ()

2. Get () and load ()

3. Querying data from a database using HQL and QBC

Package Com;import Org.hibernate.session;import Org.hibernate.sessionfactory;import org.hibernate.Transaction; Import Org.hibernate.cfg.annotationconfiguration;public class Test {public static void main (string[] args) { Sessionfactory factory = new Annotationconfiguration (). Configure (). Buildsessionfactory (); Session session = Factory.opensession (); Transaction t = session.begintransaction (); T.begin (); User User1 = (user) session.get (user.class,1); T.commit (); T.begin (); User User2 = (user) session.get (user.class,1); T.commit (); System.out.println ("User1==user2:" + (User1==user2)); Session.close ();}}

 

The results show that two objects are the same object.

The data is purged from the cache:

1. Evit () Clears the specified persisted object from the cache, releasing the memory resource occupied by the object, and the specified object becomes a free object from the persisted state to the de-state.
2. Clear () Clears all persisted objects in the cache and frees up memory resources that it occupies.

Other cache operations:

1. Contains () determines whether the specified object exists in the cache.
2. Flush () Refreshes the contents of the buffer and keeps it in sync with the database data.

Level 32 Cache

1. What is a level two cache?

Sessionfactory-level caches can be present across sessions and can be shared by multiple sessions of the session.

2. Fit into the level two cache:

(1) Frequently visited

(2) Minor changes

(3) Limited quantity

(4) data that is not very important, allowing occasional concurrent data to occur.

Such data is well suited to be placed in a level two cache.

User's rights: The number of users is small, the permissions are not many, not often changed, often be accessed.

such as organizational structures.

Think: What kind of class does the object fit into the level two cache?

Changes frequently, the class inside the object is particularly many, BBs many posts, these posts more than 20,000, which puts in the cache, cannot determine. Unless you are certain that there are some frequently accessed data volumes that are not very large and have very few changes, such data is well suited to be placed in a level two cache.

3. The two-level cache implementation principle:

How does hibernate put the data in a database into a level two cache? Note that you can think of the cache as a map object whose key is used to store the object Oid,value for storing the Pojo. First, when we use Hibernate to query data from the database, retrieve the retrieved data, hibernate puts the OID of the retrieved object into the cache key, and then puts the specific pojo into value, waiting for the next time to query the data again. Hibernate retrieves a first-level cache based on the OID you provide, retrieves a level two cache if it is configured with a level two cache, and sends an SQL statement to the database if it is not, and then puts the queried object into the cache.

Different vendors provide two levels of cache implementations, such as Eh, OS, Swarm, JBoss, and so on.

Four EH cache instances

1. Preparing the JAR Package

2. Configure Hibernate.cfg.xml

<property name= "Cache.provider_class" >org.hibernate.cache.EhCacheProvider</property>  < Property Name= "Hibernate.cache.use_second_level_cache" >true</property>

3. Create a ehcache.xml file

<?xml version= "1.0" encoding= "UTF-8"? ><ehcache xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi: nonamespaceschemalocation= "ehcache.xsd" ><diskstore path= "Java.io.tmpdir"/>< Defaultcachemaxelementsinmemory= "10000" eternal= "false" timetoidleseconds= "+" timetoliveseconds= "120" Overflowtodisk= "true" diskpersistent= "false" diskexpirythreadintervalseconds= "memorystoreevictionpolicy=" LRU "/></ehcache>

  

4. Add the Cache sub-label under the profile class tag of the object that needs to be cached

<cache usage= "Read-only"/>

5. Testing

Package Com;import Org.hibernate.session;import Org.hibernate.sessionfactory;import org.hibernate.Transaction; Import Org.hibernate.cfg.configuration;public class Test {public static void main (string[] args) {Configuration cfg = new Configuration (); Cfg.configure ("Hibernate.cfg.xml"); Sessionfactory factory = Cfg.buildsessionfactory (); Session session = Factory.opensession (); Session.begintransaction (); User User1 = (user) session.load (user.class,1); Session.gettransaction (). commit (); Session.close (); Session Session1 = Factory.opensession (); Session1.begintransaction (); User User2 = (user) session1.load (user.class,1); Session1.gettransaction (). commit (); System.out.println ("User1==user2:" + (User1==user2)); Session1.close ();//factory.close ();}}

Results:

is not the same object, this is different from the first-level cache.

In fact, the level two cache in the storage of data, do some special processing, when the data from the database loaded into memory, put into a first-class cache (before the principle of first-level caching is not elaborate), then the data into the level two cache, but the data into the two-level cache is not an object, this is different from a cache, The first-level cache is placed in a specific object, the object's properties are value, so it can be directly obtained (and is the same object), when the data into the level two cache, hibernate inside the object boxed (the specific object into the object), However, the object object still has the same properties as the original object except that the type is an object type (also known as bulk data), and that the type string of the object (the package name plus type) is also preserved in the container, and the concrete structure is The object and the type string of the object are saved by a key-value pair two-level cache (essentially a map collection so you can save by key-value pairs), but the key is a very special string, the key is the type string and the object's OID (data primary key) splicing, through the "#" Partition, specifically the class string #oid, The pair should object (object). When the data is obtained from the level two cache (which cannot be said to be an object), all keys of the level two cache are matched according to the ID and class character, and if found, an object is produced by reflection and returned to the user (program), which makes it reasonable to explain why it is not the same object, because it is reflective production, And a good explanation of why you want to save the object's class string, then why should it be reflected instead of just the object unpacking? , personally think: if the unpacking (the object is converted to a specific PO objects) is an object, level two cache is multiple thread sharing, if multiple users at the same time the same object (the memory address point of the same), will raise security issues (anyway this is not good) (from the Forum answer)

Reference: http://www.cnblogs.com/200911/archive/2012/10/09/2716873.html

 

Getting Started with Hibernate (iv)

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.