hibernate配置:
<property name="hibernate.cache.use_second_level_cache">false</property>
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
ehcache.xml配置:
<ehcache>
<!--
<cache name="myCacheRegion"
maxElementsInMemory="1000"
eternal="false"
timeToIdleSeconds="300"
timeToLiveSeconds="600"
overflowToDisk="true"
/>
<cache name="org.hibernate.cache.UpdateTimestampsCache"
maxElementsInMemory="5000"
eternal="true"
overflowToDisk="true"/>
<cache name="org.hibernate.cache.StandardQueryCache"
maxElementsInMemory="50"
eternal="false"
timeToIdleSeconds="3600"
timeToLiveSeconds="7200"
overflowToDisk="true"/>
-->
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU"
/>
</ehcache>
注:
1.是应用级别,即多进程共享,服务器没关闭,就一直在
2 缓存对象
java代码:
session = HibernateUtils.getSession();
tx = session.beginTransaction();
//Department dep=(Department)session.get(Department.class, 1);
//System.out.println(dep.getName());
Employee emp=(Employee)session.get(Employee.class, 1);
// session.setCacheMode(CacheMode.IGNORE);
System.out.println(emp.getName());
tx.commit();
session = HibernateUtils.getSession(); //不同的session,但是可以从二级缓存里取得
tx = session.beginTransaction();
Employee emp2=(Employee)session.get(Employee.class, 1);
System.out.println(emp2.getName());
System.out.println(emp2==emp);
输出:一条sql
Hibernate: select employee0_.id as id1_1_0_, employee0_.name as name2_1_0_, employee0_.age as age3_1_0_, employee0_.depart_id as depart_i4_1_0_, employee0_.skill as skill1_4_0_, employee0_.sell as sell1_3_0_, employee0_.clazz_ as clazz_0_, department1_.id as id1_0_1_, department1_.name as name2_0_1_ from ( select id, name, age, depart_id, order_col, null as skill, null as sell, 0 as clazz_ from employees union select id, name, age, depart_id, order_col, skill, null as sell, 1 as clazz_ from skiller union select id, name, age, depart_id, order_col, null as skill, sell, 2 as clazz_ from sales ) employee0_ left outer join departments department1_ on employee0_.depart_id=department1_.id where employee0_.id=?
emp name:jimmy 2015-8-20 12:24:00