1. JPA二级缓存配置
JPA中的二级缓存是在EntityManagerFactory中,但是默认EntityManagerFactory中的二级缓存是没有开启的,如果需要开启二级缓存需要做如下配置:
注:在hibernate4.3.8中是默认开启的二级缓存,无需配置;
步骤如下:
① 导入JPA二级缓存的jar包;
Jar包目录:
\hibernate-release-4.3.8.Final\lib\optional\ehcache\
ehcache-core-2.4.3.jar
hibernate-ehcache-4.3.8.Final.jar
slf4j-api-1.6.1.jar
② 对应在persistence.xml中添加如下配置:
ENABLE_SELECTIVE
③ 在对应的Entity类上加上注解:@Cacheable(true)
@Cacheable(true)
@Entitypublic classEmployee {
@Id
@GeneratedValueprivateLong id;private String name;
2. JPA集合缓存配置
集合上面加上:@Cache(usage = CacheConcurrencyStrategy.READ_WRITE),就可以缓存这个集合
@OneToMany(fetch = FetchType.LAZY, mappedBy = "department")
@org.hibernate.annotations.Cache(usage=CacheConcurrencyStrategy.READ_WRITE)//注意:hibernate集合缓存一般不用,不需要配置,配置完之后性能更差//如果一定要配置集合缓存,集合中的对象也一定要能够放到缓存中
private Set employeeSet = new HashSet();
3. JPA查询缓存配置
JPA查询缓存比较简单,只需要加上query1.setHint(QueryHints.HINT_CACHEABLE, true)即可。
Query query1 = entityManager.createQuery("select o from Employee o where o.id = ?");//把这个query1放到查询缓存中,也会到查询缓存中取
query1.setHint(QueryHints.HINT_CACHEABLE, true);
query1.setParameter(1, 1L);