日期:2014-05-16  浏览次数:20459 次

Hibernate 配置二级缓存
前几天配置了二级缓存,特此记录一下。

第一步:

添加POM.XML dependency
<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-ehcache</artifactId>
			<version>3.6.2.Final</version>
		</dependency>


第二步:

Hibernate.cfg.xml
<property name="hibernate.cache.use_second_level_cache">true</property>
		<property name="hibernate.cache.provider_class">
			org.hibernate.cache.EhCacheProvider
		</property> 


第三步:
在需要缓存的class.hbm.xml 添加声明
 <class name="test" table="CMN_test" >
    
    	<cache usage="read-write"/>
    	
        <id name="id" type="string">
            <column name="ID" length="50" />
            <generator class="assigned" />
        </id>


第三步:
编写ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--

Copyright 2011 Nicholas Blair, Eric Dalquist

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

-->

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd" updateCheck="false">

    <diskStore path="c:/ehcache" />

    <defaultCache eternal="false" maxElementsInMemory="1000"
        overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="0"
        timeToLiveSeconds="600" memoryStoreEvictionPolicy="LRU" statistics="true" />

    <cache name="com.pulse.ipmanager.egress.CmnAnumberbypass" eternal="false" 
        maxElementsInMemory="100" overflowToDisk="false" diskPersistent="false"
        timeToIdleSeconds="50" timeToLiveSeconds="300"
        memoryStoreEvictionPolicy="LRU" statistics="true" />

 </ehcache>


最后 检查一下:
getting CmnAnumberbypass instance with id: b5bd40a7-1330-4b0e-93a1-395ce84aaedd
2012-05-09 15:26:16,949 DEBUG (net.sf.ehcache.store.MemoryStore:135) - Cache: CmnAnumberbypassMemoryStore hit for CmnAnumberbypass#b5bd40a7-1330-4b0e-93a1-395ce84aaedd
2012-05-09 15:26:16,951 DEBUG (CmnAnumberbypassHome:123) - get successful, instance found