一级缓存
一级缓存是session级别的缓存,在JPA中一个entityManager对应一个session,一个session就对应一个缓存。
查询两次id为1的user
User user1 = entityManager.find(User.class, 1);
User user2 = entityManager.find(User.class, 1);
结果发现只调用了一次sql查询,因为使用了一级缓存,当第一次find就把查询到的数据放入到还缓存中,第二次再查会先去缓存中找,如果有就直接使用而不用重新查询。
如果查询一次后,关掉entityManager,再查询
User user1 = entityManager.find(User.class, 1);
entityManager.close();
entityManager = factory.createEntityManager();
User user2 = entityManager.find(User.class, 1);
发现查询了两次,因为entityManager关闭之后,其对应的缓存也就没有了。
然后有重新开启一个entityManager,就和之前的不是同一个了。
配置二级缓存
如果说一级缓存是关联session级别的局部缓存,那么二级缓存就是全局缓存。
可以跨entityManager的缓存,也就是说:就算你关闭了entityManager,缓存也依然在。
在配置文件applicationContext.xml中配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!-- 配置数据源 -->
<context:property-placeholder location="classpath:jdbc.properties" />
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
<!-- 配置其他属性(省略) -->
</bean>
<!-- 配置 JPA 的 EntityManagerFactory -->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="jpaVendorAdapter">
<bean