SSH integration Hibernate uses spring to manage hibernate level two cache, configuring hibernate4.0 above level two cache

Source: Internet
Author: User

SSH integration Hibernate uses spring to manage hibernate level two cache, configuring hibernate4.0 above level two cache

Hibernate:

Hibernate is a persistent layer framework that accesses physical databases frequently.

Improve application performance by reducing the frequency of application access to physical data sources.

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.

The hibernate cache consists of two main classes: Hibernate cache and L1hibernate level two cache L2.

The 1.Hibernate cache is also known as the "session cache".

The session can not be uninstalled, the session cache is a transaction-scoped cache (the session object's life cycle usually corresponds to a database transaction or an application transaction).

In the first-level cache, each instance of the persisted class has a unique OID.

Note: The first-level cache of Spring management hibernate is not valid during SSH consolidation.

Key Hibernate two cache, search a lot of blog results are very pit, the concept of interpretation is correct, the key is the configuration, may be my hibernate version is too high reasons, resulting in configuration failure.

The secondary cache can be broadly divided into several categories:

    • Transaction cache: Action on transaction scope, session end Cache purge, hibernate L1 cache as transaction cache, default on, we write the rollback code in a pure Hibernate project, can be rolled back because of transaction cache.
    • Application caching: Scoped to the application, shared by all transactions, depends on the life cycle of the application. So, it's a great fit to use a lightweight cache that also relies on the application lifecycle, and Ehcache is almost the best choice.
    • Cluster cache: The cache is similar to a real database shared by a cluster, and typically Redis is a good place to do cluster caching

The working principle of the second level cache;

Hibernate's L1,L2 cache works by ID, and hibernate looks in the first-level cache when it accesses an object based on its ID, or in a level two cache if it is not found.

Sessionfactory level Two caches can be partitioned into built-in caches and external caches based on functionality and purpose, with built-in caches that store mapped metadata and predefined SQL statements.

The former is a copy of the data in the mapping file, which is the SQL statement deduced from the copy. The built-in cache is read-only and therefore does not need to be synchronized with the mapping file.

The external cache is a plugin for hibernate, which is not enabled by default, which is Hibernate's L2 cache. The external cached data is a copy of the database data, and the externally cached media can be either memory or hard disk.

2, nonsense say, use external plugin ehcache to open Hibernate's Level two cache

Ehcache is a robust, concise, lightweight, pure Java Process Memory caching framework, so its presence is directly associated with the Java process.

The database is cached by copying the data in the hard disk and in the memory. Thanks to Apache's support, Ehcache is very robust.

POM node:

<!--Https://mvnrepository.com/artifact/org.hibernate/hibernate-ehcache--    <dependency>      <groupId>org.hibernate</groupId>      <artifactId>hibernate-ehcache</artifactId>      <version>5.1.7.Final</version>    </dependency>    <dependency>      <groupId> org.ehcache</groupid>      <artifactId>ehcache</artifactId>      <version>3.3.1</ Version>    </dependency>

Written by: Ehcache.xml

<?xml version= "1.0" encoding= "UTF-8"?><ehcache> <diskstore    path= "D:/ehcache"/>    < Defaultcache            maxelementsinmemory= "10000"            eternal= "false"            timetoidleseconds= "            +" timetoliveseconds= "overflowtodisk="            true "    />    <cache name=" SampleCache1           " Maxelementsinmemory= "10000"           eternal= "false"           timetoidleseconds= "timetoliveseconds="           600 "           overflowtodisk= "true"    />    <cache name= "sampleCache2"           maxelementsinmemory=           " Eternal= "true"           timetoidleseconds= "0"           timetoliveseconds= "0"           overflowtodisk= "false"    /> </ehcache>

The various properties of Ehcache are described below:

    • Name: Cache names.
    • Maxelementsinmemory: Maximum number of caches.
    • Eternal: The object is permanently valid, but if set, timeout will not work.
    • Timetoidleseconds: Sets the allowable idle time (in seconds) for an object before it expires. An optional property is used only if the Eternal=false object is not permanently valid, and the default value is 0, which means that the idle time is infinite.
    • Timetoliveseconds: Sets the time that an object is allowed to survive before it expires, with a maximum time between creation time and expiration time. Used only when the Eternal=false object is not permanently valid, the default is 0, which means that the object survives indefinitely.
    • Overflowtodisk: When the number of objects in memory reaches Maxelementsinmemory, Ehcache writes the object to disk.
    • DISKSPOOLBUFFERSIZEMB: This parameter sets the buffer size of the Diskstore (disk cache). The default is 30MB. Each cache should have its own buffer.
    • Maxelementsondisk: Maximum number of hard disk caches.
    • Diskpersistent: If the virtual machine restart period data is cached, the default is False.
    • Diskexpirythreadintervalseconds: Disk failed thread run time interval, default is 120 seconds.
    • Memorystoreevictionpolicy: When the maxelementsinmemory limit is reached, Ehcache will clean up the memory according to the specified policy. The default policy is LRU. You can set it to FIFO or LFU.
    • Clearonflush: If the maximum amount of memory is cleared.

Turn on level two caching in spring-managed sessionfactory

   <bean id= "Sessionfactory" class= "Org.springframework.orm.hibernate5.LocalSessionFactoryBean" > &lt                ;p roperty name= "DataSource" ref= "DataSource"/> <property name= "Packagestoscan" > <list> <value>zy.entity</value> </list> </property> <property N Ame= "Hibernateproperties" > <props> <prop key= "Hibernate.show_sql" &GT;TRUE&LT;/PROP&G                T <prop key= "Hibernate.dialect" >org.hibernate.dialect.MySQLDialect</prop> <prop key= "hibernate . Hbm2ddl.auto ">update</prop> <!--blog address: http://www.cnblogs.com/fsh1542115262/articles/6071470.h Tml Hibernate.current_session_context_class Three kinds of configuration--<prop key= "Hibernate.current_session_context_cla SS ">org.springframework.orm.hibernate5.SpringSessionContext</prop> <!--avoid this error message disabling conte XtualLOB creation as Createclob () method threw error:java.lang.reflect.InvocationTargetException--<pro                P key= "Hibernate.temp.use_jdbc_metadata_defaults" >false</prop> <!--Hibernate Two-level cache-- <prop key= "Hibernate.cache.use_second_level_cache" >true</prop> <prop key= "Hibernat E.cache.use_query_cache ">true</prop> <prop key=" Hibernate.cache.region.factory_class ">org.hi             Bernate.cache.ehcache.ehcacheregionfactory</prop> <!--Set the cache type, set the cache provider ehcacheregionfactory--> </props> </property> </bean>

which

<prop key= "Hibernate.cache.region.factory_class" >org.hibernate.cache.ehcache.ehcacheregionfactory</ Prop> This is the key, the reason why the previous configuration was not successful is because my hibernate version is too high, and the higher version has been replaced
Hibernate.cache.region.factory_class the specified Ehcache factory.
    • Hibernate.cache.use_second_level_cache is the L2 cache switch in Hibernate and must be true.
    • Hibernate.cache.use_query_cache is Hibernate's query cache switch and can decide whether to turn it on or not.
    • Hibernate.cache.region.factory_class the method that hosts the L2 cache, which is to select the L2 cache database. The official pit. There is a document problem from HIBERNATE4, and the document is still provider_class, in fact it has already been replaced for this method (the default hint of idea is not found, but if not added after the run, the error log can be displayed). It is important to note that you need to use the Singleton mode factory, otherwise there will be conflicting issues. The specific reasons are unclear.

There are also several options that can be turned on, including

    • Hibernate.generate_statistics generates statistical logs, if the project is being debugged, this is a good development option. Remember to shut down when actually running.
    • Hibernate.cache.provider_configuration_file_resource_path provides the path to the configuration file, and if you do not want to use the default path, you need to configure it here, in the same format as the path in Web. Xml.

Another is the need to set the cache policy in the cached entity:

Ehcache does not support transactions, there are three modes:

    • READ_ONLY: Applies to read-only and is abnormal if there is data update operation.
    • Read_write: Controlling caching with read-write locks
    • Non_strict_read_write: No lock control cache, write will conflict, suitable for a system that is difficult to write conflicts.

When used specifically, a two-level cache can be added to the database using a label like this on a hibernate persistence-generated entity.

Annotation method:

@Cache (usage = cacheconcurrencystrategy.read_write)

XML mode:
<cache usage= "Read-write"/>  includes class level and collection level;
Typically, the cache is used for multiple read and write-less tables, in which the most efficient and best-fit behavior of the cache itself should be the read_only pattern, which is to use the cache when reading, emptying the cache when a write occurs.

Test: The default method of using level two caching in Hibernate load () and iterator () methods
This is configured using the Load () method:
My DAO Layer method:
    Public Bill Load () {        Session session = This.sessionFactory.openSession ();        Bill load = session.load (bill.class);       /* IF (! hibernate.isinitialized (load)) {             hibernate.initialize (load);        }        Session.close (); */        return load;    }

    /**     * Test Hibernate's Level two cache     *    /@Test public    void Testtwocache () {        ApplicationContext context = new Classpathxmlapplicationcontext ("Spring-hiberanate.xml");        Billservice service= (Billservice) Context.getbean ("Billserviceimpl");        Bill load = Service.load ();        SYSTEM.OUT.PRINTLN (load);        System.out.println (Load.getbname ());        System.out.println ("----------------------------------");  Note that this is not a first-level cache of calls, as the first-level cache of hibernate in SSH integration is invalidated, including the SSM is MyBatis        billservice service1= (billservice) Context.getbean ("Billserviceimpl");        Bill load1 = Service.load ();        System.out.println (Load1.getbname ());    }

Operation Result:

Hibernate:select bill0_.bid as bid1_1_0_, Bill0_.bmoney as bmoney2_1_0_, bill0_.bname as bname3_1_0_, bill0_.createtime a S createti4_1_0_, Bill0_.hscode as hscode5_1_0_, bill0_.paystate as paystate6_1_0_, Bill0_.scount as scount7_1_0_, bill0_ . Sunit as sunit8_1_0_, bill0_.supid as supid9_1_0_ from Bill Bill0_ where bill0_.bid=? [email protected] Kiwi Shanxi----------------------------------kiwi Shanxi

It is clear that Hibernate's level two cache setting is successful;

Item: Forget it. Too low if necessary, leave a comment;

SSH integration Hibernate uses spring to manage hibernate level two cache, configuring hibernate4.0 above 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.