jpa二级缓存

jpa的一级和二级缓存
一级缓存:比如:
Customer customer1 = entityManager.find(Customer.class, 1);
Customer customer2 = entityManager.find(Customer.class, 1);
那么,在查询中,其实只查询了,一次,因为第二次其实已经在一级缓存中了
但是,
Customer customer1 = entityManager.find(Customer.class, 1);
transaction.commit();
entityManager.close();
entityManager = entityManagerFactory.createEntityManager();
transaction = entityManager.getTransaction();
transaction.begin();
Customer customer2 = entityManager.find(Customer.class, 1);
这样,就会查询2次SQL,因为他们在不同的entityManager中。
二级缓存,就是要在不同的entityManager中,只查询一次
这里就需要使用到hibernate 的二级存在方法,需要ehcache,至少有4步,一步是加上jar并写ehcache.xml,在src目录下,另一步是配置hibernate:
<property name="hibernate.cache.use_second_level_cache" value="true"/>
<property name="hibernate.cache.region.factory_class" value="org.hibernate.cache.ehcache.EhCacheRegionFactory"/>
<property name="hibernate.cache.use_query_cache" value="true"/>
其中:
配置二级缓存的策略
ALL:所有的实体类都被缓存
NONE:所有的实体类都不被缓存.
ENABLE_SELECTIVE:标识 @Cacheable(true) 注解的实体类将被缓存
DISABLE_SELECTIVE:缓存除标识 @Cacheable(false) 以外的所有实体类
UNSPECIFIED:默认值,JPA 产品默认值将被使用

第三步,在实体映射配置的后面加上
<shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode>

第四步,在实体类上加上类名之上,加上 @Cacheable(true)

二级缓存处理刷新重复查询问题:

@QueryHints({@QueryHint(name=org.hibernate.ejb.QueryHints.HINT_CACHEABLE,value="true")})
@Query("from Department d")
List<Department> getAll();

@Transactional(readOnly=true)
public List<Department> getAll(){
return departmentRepository.getAll();

}
@RequestMapping(value="/emp",method=RequestMethod.GET)
public String Input(Map<String, Object> map) {
map.put("departments", department.getAll());
map.put("employee", new Employee());
return "emp/input";
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值