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"?>
<diskStore path="" />
<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: *******
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 = debug View Log

1. In the category path ehcache.xml:


<! - 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 - Default temp file path ->
<diskStore path=""/>

<! - 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.

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

<! - See # mozTocId258426 for how to configure caching for your objects ->
</ ehcache>

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

<! - Hibernate SessionFactory ->
<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">
<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=""> 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
<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>
<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" />

分类:Java 时间:2009-08-22 人气:1850
blog comments powered by Disqus


  • 前端性能优化:使用Data URI代替图片SRC 2013-07-07

    日期:2013-7-6 来源 提升页面大小的效率,不仅仅是取决于使用精灵或是压缩代码,给定页面的请求数量在前端性能中也占有了很不小的重量.减少请求可以让你的网站加载更快,而其中一种减少页面请求的方法就是用Data URI代替图片的src属性: <!-- 以前的写法 --> <img src="/images/logo.png" /> <!-- 使用data URI的写法 --> <img src="data: im

  • Memory Notification: Library Cache Object loaded into SGA 2010-08-02

    Question: alert_SID.log appear Memory Notification: Library Cache Object loaded into SGA Heap size 2289K exceeds notification threshold (2048K) Oracle10g, in the large load object into the library cache, it will record more than a warning. In version

  • Extjs3 + MySQL backend database implementation province city secondary linkage 2010-10-14

    Extjs+MySQL Background database provinces city-level linkage The following basic code : Ext.onReady(function(){ Ext.QuickTips.init(); Ext.BLANK_IMAGE_URL = "../js/Ext/resources/images/default/s.gif"; var storeProvince = new{

  • In the data structure before planning the design of XML messages 2010-03-31

    Web services use XML messages to transfer data technology. If you want to design a database structure, you probably will not let your instrument go automatically completion, but manual adjustments to Jinxing to ensure maximum efficiency, the author o

  • When the bulk import data, do not want to have to take each sequence, to generate volume in memory 2010-05-05

    Experience, notes: Can define a increment_value value, volume data into the database before the start to take a sequence, The first getNewId, taking from the database sequence, if taken to 1, then multiplied by 10 (increment_value) return, which is t

  • php parsing xml file (no need to download other libraries) to the array data analysis 2010-02-19

    <?php $xml ="1.xml"; $dom = new DOMDocument(); $dom->load($xml); $root = $dom->documentElement; $arr=array(); foreach ($root->childNodes as $item) { if($item->hasChildNodes()){ $tmp=array(); foreach($item->childNodes as $one){

  • Hibernate + ehcache secondary cache 2009-05-12

    Hibernate + ehcache secondary cache 2006-09-02 05:00 Author: Source: csdn duty Edit: Ark 1, the first set EhCache, set up configuration files ehcache.xml, the default position at the class-path, you can put the src directory: < ?xml version="1.0"

  • Hibernate + ehcache 2 Cache 2010-03-29

    1, first set EhCache, the establishment of the configuration file ehcache.XML, the default location of class-path, you can put your src directory: < ?xml version="1.0" encoding="UTF-8"? > <ehcache> <diskStore path ="

  • Memcached data is kicked (evictions> 0) Phenomenon 2011-01-13

    Many students may be familiar with the LRU Memcached-out algorithm, which is within the slab, if the slabs have been allocated all the space, even if the slab inside another space, the data may still kicking. You can understand the slab for the class

  • Android Notes (a): Android project directory description 2011-05-28

    Andrew installed the SDK, the new program AVD for debugging, you can create and run inside the Eclipse Andrews program. This section as a whole to understand the basic processes and new projects in the Eclipse project directory Atradius and specific

iOS 开发

Android 开发

Python 开发



PHP 开发

Ruby 开发






Javascript 开发

.NET 开发



Copyright (C), All Rights Reserved. 版权所有 闽ICP备15018612号

processed in 0.225 (s). 12 q(s)