Hibernate学习:查询缓存

一:查询缓存的配置


(1)在Hibernate配置文件中打开查询缓存
 <!-- 打开查询缓存 -->
<property name=”hibernate.cache.use_query_cache”>true</property>
注意:查询缓存是依赖二级缓存的,注意先打开二级缓存


(2)query.setCacheable(true)
List<User> list  = (List<User>)session.createQuery("from User").setCacheable(true).list();
List<User> list2 = (List<User>)session.createQuery("from User").setCacheable(true).list();

 

二:单元测试

@org.junit.Test
	@SuppressWarnings({ "unused", "unchecked" })
	public  void  testQueryCahce(){
		Session session = factory.openSession();
		session.beginTransaction();
		List<User> list  = (List<User>)session.createQuery("from User").setCacheable(true).list();
		List<User> list2 = (List<User>)session.createQuery("from User").setCacheable(true).list();
		session.getTransaction().commit();
		session.close();
	}


输出结果:只输出一条sql语句,证明查询缓存起作用了!


Hibernate: 
    select
        user0_.id as id0_,
        user0_.group_id as group3_0_,
        user0_.name as name0_ 
    from
        User user0_
afterClass

你可能感兴趣的:(Hibernate,cache,缓存)