The use of EhCache

What is 1.EhCache
Hibernate's EhCache is one of the secondary cache, you can query from the data storage disk or in memory to save the next time the same query once again query the database, the database significantly reduce the pressure;

Note the use of 2.EhCache point when using Hibernate to modify the table data (save, update, delete, etc.), then automatically EhCache cache on the table to delete all cache all out (so to achieve synchronization) . However, often modify the table data may be lost meaning cache (the database can not alleviate the pressure);

3.EhCache use 3.1 fewer occasions to update table data EhCache generally less used in the implementation of the table write operations (including update, insert, delete, etc.) [Hibernate are secondary cache such];
3.2 pairs of concurrent requests is not very strict in the case of the two machine's cache is not real-time synchronization;

4. The realization of the project 4.1 project to add the src directory ehcache.xml document reads as follows:
<? xml version = "1.0" encoding = "UTF-8"?>
<ehcache>
<diskStore path="java.io.tmpdir" />
<defaultCache maxElementsInMemory = "5 "<!-- cache can store records of the total volume ->
eternal = "false "<!-- cache is never destroyed ->
overflowToDisk = "true "<!-- when the data in the cache when the maximum, whether or not to cache data written to disk ->
timeToIdleSeconds = "15 "<!-- when the cache exceeds the value of idle time, the automatic destruction of the cache ->
timeToLiveSeconds = "120 "<!-- cache created after the arrival of the automatic destruction of the cache ->
/>
</ ehcache>
4.2 in the mapping tab Hibernate.cfg.xml above plus the following:
<property name="show_sql"> true </ property>
<property name="hibernate.cache.provider_class"> org.hibernate.cache.EhCacheProvider </ property>
<property name="hibernate.cache.use_query_cache"> true </ property>
4.3 in the bean to the hbm.xml cache file class labels to add the following:
<cache usage="read-only" /> <! - can also read and write ->
4.4 create a DAO, which reads as follows:
Session s = HibernateSessionFactory.getSession ();
Criteria c = s.createCriteria (Xyz.class);
c.setCacheable (true); / / This must be System.out.println ( "first reading");
List l = c.list ();
System.out.println (l.size ());
HibernateSessionFactory.closeSession ();

s = HibernateSessionFactory.getSession ();
c = s.createCriteria (Xyz.class);
c.setCacheable (true); / / This must be System.out.println ( "read the second time");
l = c.list ();
System.out.println (l.size ());
HibernateSessionFactory.closeSession ();
4.5 At this time you will see the information printed (for the second time did not read the Treasury):
Read the first Hibernate: *******
13
The second reading 13

Spring + hibernate configuration to use ehcache as a second-level cache

A large amount of data flow web application performance issues are common reasons, and the cache has been optimized for a wide range of database applications. cache is designed to save from the database through the data to reduce the load applications and data flows between databases. Database access only when retrieval of data in cache is not available when necessary. hibernate can be used two different kinds of object caching: first-level cache and second-level cache. first-level cache and the Session object, which is the second-level cache and Session Factory object.

By default, hibernate has to use services based on each of the first-level cache. Hibernate with the main first-level cache to reduce services in a number of sql queries. For example, if an object in the same services have been modified several times, hibernate will only generate a modified, including all UPDATE SQL statement. In order to reduce the data flow, second-level cache in the Session Factory level between the different services of the load object, these objects can be used for the entire application, not only for the current user running the query. In this way, each query will return has been in the load object in the cache, to avoid the potential of one or more database transaction.

Download ehcache , Hibernate3.2 must be able to support more than ehcache1.2. Can modify the log4j configuration file log4j.logger.net.sf.hibernate.cache = debug View Log

1. In the category path ehcache.xml:

<ehcache>

<! - Sets the path to the directory where cache. Data files are created.

If the path is a Java System Property it is replaced by
its value in the running VM.

The following properties are translated:
user.home - User's home directory
user.dir - User's current working directory
java.io.tmpdir - Default temp file path ->
<diskStore path="java.io.tmpdir"/>

<! - Default Cache configuration. These will applied to caches programmatically created through
the CacheManager.

The following attributes are required:

maxElementsInMemory - Sets the maximum number of objects that will be created in memory
eternal - Sets whether elements are eternal. If eternal, timeouts are ignored and the
element is never expired.
overflowToDisk - Sets whether elements can overflow to disk when the in-memory cache
has reached the maxInMemory limit.

The following attributes are optional:
timeToIdleSeconds - Sets the time to idle for an element before it expires.
ie The maximum amount of time between accesses before an element expires
Is only used if the element is not eternal.
Optional attribute. A value of 0 means that an Element can idle for infinity.
The default value is 0.
timeToLiveSeconds - Sets the time to live for an element before it expires.
ie The maximum time between creation time and when an element expires.
Is only used if the element is not eternal.
Optional attribute. A value of 0 means that and Element can live for infinity.
The default value is 0.
diskPersistent - Whether the disk store persists between restarts of the Virtual Machine.
The default value is false.
diskExpiryThreadIntervalSeconds-The number of seconds between runs of the disk expiry thread. The default value
is 120 seconds.
->

<defaultCache
maxElementsInMemory = "10000"
eternal = "false"
overflowToDisk = "true"
timeToIdleSeconds = "120"
timeToLiveSeconds = "120"
diskPersistent = "false"
diskExpiryThreadIntervalSeconds = "120" />

<! - See http://ehcache.sourceforge.net/documentation/ # mozTocId258426 for how to configure caching for your objects ->
</ ehcache>

2.applicationContext-hibernate.xml in Hibernate SessionFactory configuration:

<! - Hibernate SessionFactory ->
<bean>
<property name="dataSource" ref="dataSource"/>
<property name="configLocation"> <value> classpath: hibernate.cfg.xml </ value> </ property>
<! - The property below is commented out b / c it doesn't work when run via
Ant in Eclipse. It works fine for individual JUnit tests and in IDEA??
<property name="mappingJarLocations">
<list> <value> file: dist / appfuse-dao.jar </ value> </ list>
</ property>
->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect"> @ HIBERNATE-DIALECT @ </ prop>
<!--< prop key = "hibernate.show_sql"> true </ prop> ->
<prop key="hibernate.max_fetch_depth"> 3 </ prop>
<prop key="hibernate.hibernate.use_outer_join"> true </ prop>
<prop key="hibernate.jdbc.batch_size"> 10 </ prop>
<prop key="hibernate.cache.use_query_cache"> true </ prop>
<prop key="hibernate.cache.use_second_level_cache"> true </ prop>
<prop key="hibernate.cache.provider_class"> org.hibernate.cache.EhCacheProvider </ prop>
<! --
<prop key="hibernate.use_sql_comments"> false </ prop>
->
<! - Create / update the database tables automatically when the JVM starts up
<prop key="hibernate.hbm2ddl.auto"> update </ prop> ->
<! - Turn batching off for better error messages under PostgreSQL
<prop key="hibernate.jdbc.batch_size"> 0 </ prop> ->
</ props>
</ property>
<property name="entityInterceptor">
<ref local="auditLogInterceptor"/>
</ property>
</ bean>
Description: If you do not set the "query cache", then use the hibernate cache will load () method to obtain a single persistent object, the cache if you want to use the findall (), list (), Iterator (), createCriteria (), createQuery () method to obtain data such as result set, it need to do hibernate.cache.use_query_cache true

3.model class *. hbm.xml used to generate Xdoclet's cache xml tags that <cache usage="read-only"/>

/ **
* @ Hibernate.class table = "WF_WORKITEM_HIS"
* @ Hibernate.cache usage = "read-write"
*
* /

4. The "query cache", the need for coding in the program:

getHibernateTemplate (). setCacheQueries (true);
return getHibernateTemplate (). find (hql);

The use of spring and hibernate and ehcache configuration query cache

1, applicationContext.xml
<prop key="hibernate.cache.provider_class"> org.hibernate.cache.EhCacheProvider </ prop>
<prop key="hibernate.cache.use_query_cache"> true </ prop>
These two lines added in hibernateProperties
<bean>
<property name="sessionFactory">
<ref bean="sessionFactory" />
</ property>
<property name="cacheQueries">
<value> true </ value>
</ property>
</ bean>

Add to applicationcontext.xml in this bean. DAO in all of the bean, the changes are as follows
<property name="sessionFactory">
<ref bean="sessionFactory" />
</ property>
Changed
<property name="hibernateTemplate">
<ref bean="hibernateTemplate" />
</ property>

2, ehcache.xml file on the root directory of your classes

3, pojo configuration ehcache.xml relationship with com.ce.ceblog.pojos.CeblogJournal as an example to configure the CeblogJournal.hbm.xml:
<class name="CeblogJournal" table="CEBLOG_JOURNAL" lazy="false">
<cache usage="read-write" region="ehcache.xml In the name of the attribute value "/>
Note: This is a need to keep up with the following labels in the class, the other location is invalid.

The main documents are as follows Ehcache.xml
<defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="1" timeToLiveSeconds="1" overflowToDisk="true" />
<cache name="com.ce.ceblog.pojos.CeblogJournal" maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="300" timeToLiveSeconds="600" overflowToDisk="true" />
  • del.icio.us
  • StumbleUpon
  • Digg
  • TwitThis
  • Mixx
  • Technorati
  • Facebook
  • NewsVine
  • Reddit
  • Google
  • LinkedIn
  • YahooMyWeb

Related Posts of The use of EhCache

  • hibernate to use the principle of

    The use of hibernate, implementation of data persistence. Has the following several processes. One configuration database connection information. Hibernate.config 2 configuration mapping. 3 use: the use of the process are the following steps: 3.1: Ge ...

  • Servlet brief introduction

    Servlet brief introduction: Servlet is a small application server Are used to complete the B / S architecture, the client requests the response to treatment Platform independence, performance, able to run thread Servlet API for Servlet provides the s ...

  • Spring2.0 + hibernate3.1 + log4j + mysql demo

    applicationContext.xml Non-attachment jar package, necessary friends can send an email to todd.liangt @ gmail.com

  • Based on JDBC, JPA Annotation achieve simple CRUD Generic Dao

    The origin of ideas are pretty long history of reasons: [Use iBATIS history] The use of iBATIS has been a long time, the system is to use the CRUD template tool to generate the code, although there are tools to generate, but looked at a lot of CRUD the Sq

  • Hibernate secondary cache

    Hibernate cache: 2-bit cache, also known as process-level cache or SessionFactory level cache, secondary cache can be shared by all of the session Cache configuration and the use of: Will echcache.xml (the document code in hibernate package directory ...

  • The level Hibernate cache

    Hibernate cache level: (1) a cache is very short and the session life cycle consistent, also known as session-level cache-level cache or transaction-level cache (2) Ways of Supporting level cache: get (); load (); iterator (); only entity object cach ...

  • Hibernate's lazy strategy

    hibernate Lazy strategy can be used in: <class> tag, it can be true / false Tags can <PROPERTY> values true / false type of necessary tools to enhance <set> <list> can tag values true / false / extra <many-to-one> <on ...

blog comments powered by Disqus
Recent
Recent Entries
Tag Cloud
Random Entries