hibernate查询缓存不能缓存实体对象吗?

massjcy 发布于 2015/01/31 19:59
阅读 603
收藏 1

描述:Java web项目,SSH框架中,hibernate二级缓存和查询缓存都配置了,hibernate查询缓存使用EHCache提供的缓存机制

问题:是不是缓存只能存普通属性集而不能存实体对象集啊?我试了好几次实体对象集好像都没有缓存似的,第二次查询还是发送SQL语句,我测试的时候list()和iterate()方法都试了,结果都是重新查询,请大神们赐教!!



@Test
public void testQueryCache(){
    ApplicationContext acf = new ClassPathXmlApplicationContext("applicationContext.xml");
    SessionFactory sessoinFactory = (SessionFactory)acf.getBean("sessionFactory");
    Session session = sessoinFactory.openSession();
    session.beginTransaction();
    String hql = "from User where id = 1";
    session.createQuery(hql).setCacheable(true).list();

    Session session2 = sessoinFactory.openSession();
    session2.beginTransaction();
    String hql2 = "from User where id = 1";
    session2.createQuery(hql2).setCacheable(true).list();

    Session session3 = sessoinFactory.openSession();
    session3.beginTransaction();
    String hql3 = "from User where id = 1";
    session3.createQuery(hql3).setCacheable(true).list();

}

控制台显示的SQL语句:

Hibernate: select user0_.id as id0_, user0_.loginName as loginName0_, user0_.password as password0_, user0_.role as role0_ from register.user user0_ where user0_.id=1


Hibernate: select user0_.id as id0_0_, user0_.loginName as loginName0_0_, user0_.password as password0_0_, user0_.role as role0_0_ from register.user user0_ where user0_.id=?


Hibernate: select user0_.id as id0_0_, user0_.loginName as loginName0_0_, user0_.password as password0_0_, user0_.role as role0_0_ from register.user user0_ where user0_.id=?


加载中
0
调皮的XD
调皮的XD
hibernate可以缓存对象的,你配置应该没有配对
m
massjcy
实体类我配置了,用的annotation,usage为可读写,cache(usage=........readwrite),这样行吗?ehcache.xml中怎么配置呢?能把你的配置贴上去吗?谢谢你
调皮的XD
调皮的XD
回复 @massjcy : 还有配置实体对象缓存的,就是在类上配置,还有在ehcache.xml里面加上需要被缓存对象的信息
m
massjcy
是不是还需要特殊的配置呢?我这里的配置普通属性集合是可以缓存的。请赐教
0
调皮的XD
调皮的XD
<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
	<diskStore path="java.io.tmpdir" />
	<defaultCache maxElementsInMemory="10000" eternal="false"
		timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="false" />
		
	<cache name="myCache" maxElementsOnDisk="20000"
		maxElementsInMemory="2000" eternal="true" overflowToDisk="true"
		diskPersistent="true" />


	
	<cache name="com.XXX.model.User" maxElementsOnDisk="10000"
		maxElementsInMemory="2000" eternal="true" overflowToDisk="true"
		diskPersistent="true" />
	
	<cache name="com.XXX.model.Resource" maxElementsInMemory="2000" 
		eternal="true" overflowToDisk="false"/>
	
					
	<cache name="org.hibernate.cache.internal.StandardQueryCache"
		maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="300"
		timeToLiveSeconds="4200" overflowToDisk="true" />


	<cache name="org.hibernate.cache.spi.UpdateTimestampsCache"
		maxElementsInMemory="5000" eternal="true" timeToIdleSeconds="0"
		timeToLiveSeconds="0" overflowToDisk="false" />
</ehcache>



返回顶部
顶部