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中添加如下配置:
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" version="2.0"> <persistence-unit name="cn.yif.jpa04" transaction-type="RESOURCE_LOCAL"> <shared-cache-mode>ENABLE_SELECTIVEshared-cache-mode> <properties> <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" /> <property name="hibernate.connection.url" value="jdbc:mysql:///jpa04_0523" /> <property name="hibernate.connection.username" value="root" /> <property name="hibernate.connection.password" value="admin" /> <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" /> <property name="hibernate.hbm2ddl.auto" value="validate" /> <property name="hibernate.show_sql" value="true" /> <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"/> properties> persistence-unit> persistence>
③ 在对应的Entity类上加上注解:@Cacheable(true)
@Cacheable(true) @Entity public class Employee { @Id @GeneratedValue private Long 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 SetemployeeSet = 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);