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();
@Query("from Department d")
List<Department> getAll();
@Transactional(readOnly=true)
public List<Department> getAll(){
return departmentRepository.getAll();
}
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";
}
public String Input(Map<String, Object> map) {
map.put("departments", department.getAll());
map.put("employee", new Employee());
return "emp/input";
}