Hibernate Level Two cache

Source: Internet
Author: User
Tags bulk insert

Hibernate Cache

• Cache: A very general concept in the computer field. It is between an application and a persistent data storage source, such as a file on a hard disk or a database, to reduce the frequency with which the application directly reads and writes to the persistent data storage source, thereby improving the performance of the application. The data in the cache is a copy of the data in the data storage source. The cached physical media is typically a two-level cache in memory hibernate – The first level of cache is the Session-level cache, which is a transactional-scoped cache. This level of cache is managed by Hibernate – the second level of caching is the sessionfactory level of caching, which is a cache of  sessionfactory levels that belong to the process-wide cache sessionfactory can be divided into two categories: – Built-in cache: Hibernate comes with and cannot be uninstalled. Normally during hibernate initialization, hibernate places the mapping metadata and predefined SQL statements into the sessionfactory cache, where the mapping metadata is a copy of the data in the mapping file (the data in the. hbm.xml file). The built-in cache is read-only. – External cache (level two cache): a configurable cache plug-in. By default, Sessionfactory does not enable this cache plug-in. The data in the external cache is a copy of the database data, and the physical media of the external cache can be memory or hard disk using Hibernate's level two cache • Data that fits into the level two cache: – Rarely modified – not very important data, allowing occasional concurrency problems • Not suitable for data in level two cache: – Often modified – financial data, never allow concurrency issues – data shared with other applications   concurrent access policies for two-level cache • There are also various concurrency issues that can occur when two concurrent transactions access the same data for a persistent layer's cache. • Two-level cache allows you to set the following 4 Types of concurrent access policies, each of which corresponds to a transaction isolation level – non-strict read/write (Nonstrict-read-write): The consistency of the cache with the data in the database is not guaranteed. Provides the Read uncommited transaction isolation level, which can be used for data that is rarely modified and allows dirty reads-read-write (Read-write): Provides the read commited data isolation level. For data that is often read but seldom modified, this can be used to Off-type because it prevents dirty reads – Transactional (transactional): Only applicable in managed environments. It provides the repeatable READ transaction isolation level.For data that is often read but rarely modified, this isolation type can be used because it prevents dirty reads and non-repeatable reads – Read-only (READ-ONLY): Provides the Serializable data isolation level, which can be managed with this access policy for data that has never been modified Hibernate's Level two cache Hibernate level Two cache is a process or cluster-wide cache • The two-level cache is a configurable plugin, Hibernate allows the following types of cache plug-ins: –ehcache: Can be used as a process-wide cache, The physical media that holds the data can make memory or hard disk support for Hibernate's query cache –opensymphony Oscache: As a process-wide cache, the physical media that holds the data can make memory or hard disks, provide a rich cache data expiration policy, Hibernate's query cache provides support for –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, support Hibernate's query cache • 4 Concurrent access policies supported by the cache plug-in (X for support, blank for unsupported) configure process-wide level two caching • Steps to configure a process-wide level two cache: – Select the appropriate cache plug-in: EHCache (Jar package and configuration file), and compiler profile – in Hibernate Configuration file, enable level two caching and specify and EHCache the corresponding cache adapter – Select a persistence class that requires a level two cache, set its two-level cache concurrency Access policy <class> element's cache child element indicates that Hibernate caches the simple properties of the object, However, the collection properties are not cached, and if you want to cache the elements in the collection properties, you must include the <cache> child elements in the <set> element • Use the cache with <class-cache/> node configuration in the Hibernate configuration file  ehcache.xml <diskstore&gt: Specify a directory: When Ehcache writes data to the hard disk, it writes the data to this directory. <defaultcache>: Set default data Expiration policy for the cache · <cache> sets the data expiration policy for the specific named cache. Each named cache represents a cache area • Cache region: A cache block with a name that can set a different cache policy for each cache block. If you do not set anyCache area, all cached objects will use the default cache policy. That is: <defaultcache.../> hibernate holds different classes/collections in different cache areas. – For a class, the name of the zone is the class name. For example: com.atguigu.domain.customer– for a collection, the name of the zone is the class name plus the property name. such as the attribute of the Com.atguigu.domain.customer.orders cache element   –name: Sets the name of the cache, its value is the fully qualified name of the class or the name of the collection of classes –maxinmemory: Set the maximum number of objects that can be stored in a memory-based cache –eternal: Sets whether the object is permanent, true means never expires, and ignores the timetoidleseconds and Timetoliveseconds properties; The default value is False–timetoidleseconds: Sets the maximum amount of time the object is idle, in seconds, when the object expires. When an object expires, Ehcache clears it from the cache. If this value is 0, the object can be idle indefinitely. –timetoliveseconds: Sets the object to live for the longest time, over this time, the object expires.
If this value is 0, the object can exist indefinitely in the cache. The property value must be greater than or equal to the Timetoidleseconds property value –overflowtodisk: If the number of objects in the memory-based cache reaches the upper limit, whether to write the overflow object to the hard disk-based cache    Query Caching • For frequently used query statements, if query caching is enabled, Hibernate will store the query results in the query cache the first time the query statement is executed. When you execute the query statement again later, you only need to get the query results from the cache to improve query performance • Query caching is used for applications where query statements are used frequently – rarely insert, delete, and update the data retrieved from a query statement • Steps to enable query caching – Configure level two caching, Because query caching relies on level two caching – Enable query caching in Hibernate profiles – Call the Setcacheable () method   Timestamp cache area of query for queries that want to enable query caching · The timestamp cache area holds the time stamp for inserting, updating, or deleting a table related to the query results .  Hibernate Determines whether the cached query result expires by using the timestamp cache area, and it runs as follows: –t1 time to execute the query operation, the query results stored in The Querycache zone, which records the time stamp for the zone, updates the table associated with the query results at t1–t2 time, and Hibernate stores T2 in the Updatetimestampcache area. –t3 time to execute the query results before you compare Queryca The time stamp of the Che area and the timestamp of the Updatetimestampcache area, if T2 >t1, discard the query result that was stored in the Querycache area, then query the data in the database again, and then store the result in the Querycache area; If T2 < T1, get query results directly from Querycache  query Interface Iterate () method query Interface iterator () method – Same as list () the query operation can be performed by the –list () method. The SQL statement contains all the fields of the data table corresponding to the entity class –iterator () method executes a SQL statement that contains only the ID field of the data table corresponding to the entity class – when iterating through the result set, the method first checks to see if there is an object of a specific OID in the Session cache and the level two cache, if any , itReturns the object directly, and loads a specific entity object into the database with the corresponding SQL Select statement if the object does not exist • In most cases, you should consider using the list () method to perform a query operation. The iterator () method can improve query performance only if the following conditions are true: – A large number of fields are included in the data table to be queried – A level two cache is enabled and the two cache may already contain objects to be queried   managed session hibernate  It provides three ways to manage Session objects –session object life cycle and local thread binding –session object life cycle and JTA transaction binding –hibernate Delegate Program Management Session Object Lifecycle • Configuration in Hibernate File, the Hibernate.current_session_context_class property is used to specify the session management mode, and the optional values include the lifetime of the –thread:session object and the local thread binding –jta*: Session The lifecycle of an object is associated with a JTA transaction binding managed:hibernate a delegate program to manage session the life cycle of an objectthe lifetime of the Session object is bound to the local thread• If you set the Hibernate.current_session_context_class property value of the Hibernate profile to thread, hibernate will manage it in a way that is bound to the local thread session Hibernate binds the Session to the local thread by pressing the rule-when a thread (Threada) first invokes the Getcurrentsession () method of the Sessionfactory object, the method creates a new session ( Sessiona) object that binds the object to Threada and returns Sessiona – when Threada again calls the Sessionfactory () method of the Getcurrentsession object, the method returns Sessiona Object – When Threada commits the transaction associated with the Sessiona object, Hibernate automatically flush the cache of the Sessiona object, then commits the transaction and closes the Sessiona object. When Threada revokes the transaction associated with the Sessiona object, the Sessiona object is also automatically closed – if Threada again calls the Sessionfactory () method of the Getcurrentsession object, the method creates a new Session (SESSIONB) object that binds the object to Threada and returns the SESSIONB back    bulk processing data • Batch processing data refers to the processing of large amounts of data in a transaction. • Bulk operations at the application level, mainly in the following ways: – Through session– the Save () and update () Methods for batch operations via the hql– through statelesssession– through the JDBC api  through the Session will store the processed objects in their own cache. If you are working with a large number of persisted objects through a Session object, you should clear the cache of objects that have been processed and will not be accessed in a timely manner. The specific practice is to immediately call the flush () method to flush the cache after processing an object or a small batch object, and then clear the cache in the call to the clear () method • The session is constrained by the following constraints – need to set JD in the   Hibernate profile The number of BC single batch processing should be guaranteed for eachThe number of batches of SQL statements sent to the database is consistent with the Batch_size attribute – if the object uses the "identity" identifier generator, hibernate cannot do bulk insert operations at the JDBC layer – it is recommended to turn off Hibernate's level two slow Save/BULK INSERT data:
NULL ;  for (int i = 0; i < 100000; i++) {    new person ();    P.setname ("--" +i);        Session.save (p);     if ((i+1)%20 = = 0) {        session.flush ();        Session.clear ();    }}

• Batch update: When a batch update is in progress, it is obviously undesirable to load all objects into the Session cache and then cache the one by one update, using the scrollable result set org.hibernate.ScrollableResults, The object does not actually contain any objects, only cursors that are used to locate records online. It will only load the appropriate object into the database when the program iterates through the specific element that accesses the Scrollableresults object. Org.hibernate.scrollableresults object is returned by the scroll method of Query
        scrollableresults sr  = Session.createquery ("from"). Scroll ();         int count = 0;          while (Sr.next ()) {            = (person) sr.get (0);            Person.setname (Person.getname ()+ "* * * *");                         if (((count++) +1)%100==0) {                session.flush ();                Session.clear ();            }        }

Bulk Operation via HQL

• Note: HQL only supports INSERT into ... Insert statement in the form of SELECT, but does not support insert INTO ... The INSERT statement in the VALUES form.  Therefore, the bulk insert operation cannot be performed using HQL. Bulk operation via statelesssession • In form, the statelesssession is similar to the use of the session. Statelesssession compared to session, there are the following differences: –statelesssession is not cached, the object that is loaded, saved, or updated by Statelesssession is in a free state. –statelesssession does not interact with Hibernate's second-level cache. – When you call the Save (), update (), or delete () method of Statelesssession, these methods execute the corresponding SQL statement immediately, and do not plan to execute only one SQL statement –statelesssession does not perform a dirty check. Therefore, after modifying the Customer object properties, you also need to call Statelesssession's update () method to update the data in the database. –statelesssession does not perform any cascading operations on the associated objects. – Two object memory addresses are obtained by using the same Statelesssession object two times to load the OID 1 customer object. –statelesssession's actions can be captured by the Interceptor interceptor, but ignored by Hibernate's event handling system.

Hibernate Level Two cache

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.