首先,下载样例工程chapter3-2-2。本例经过spring-data-jpa实现了对User用户表的一些操做,若没有这个基础,能够先阅读《使用Spring-data-jpa简化数据访问层》一文对数据访问有所基础。html
为了更好的理解缓存,咱们先对该工程作一些简单的改造。git
application.properties
文件中新增spring.jpa.properties.hibernate.show_sql=true
,开启hibernate对sql语句的打印spring
修改单元测试ApplicationTests
,初始化插入User表一条用户名为AAA,年龄为10的数据。并经过findByName函数完成两次查询。sql
@RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(Application.class) public class ApplicationTests { @Autowired private UserRepository userRepository; @Before public void before() { userRepository.save(new User("AAA", 10)); } @Test public void test() throws Exception { User u1 = userRepository.findByName("AAA"); System.out.println("第一次查询:" + u1.getAge()); User u2 = userRepository.findByName("AAA"); System.out.println("第二次查询:" + u2.getAge()); } }
Hibernate: insert into user (age, name) values (?, ?) Hibernate: select user0_.id as id1_0_, user0_.age as age2_0_, user0_.name as name3_0_ from user user0_ where user0_.name=? 第一次查询:10 Hibernate: select user0_.id as id1_0_, user0_.age as age2_0_, user0_.name as name3_0_ from user user0_ where user0_.name=? 第二次查询:10
在测试用例执行前,插入了一条User记录。而后每次findByName调用时,都执行了一句select语句来查询用户名为AAA的记录。数据库
pom.xml
中引入cache依赖,添加以下内容: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency>
@EnableCaching
注解开启缓存功能,以下: @SpringBootApplication @EnableCaching public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
@CacheConfig(cacheNames = "users") public interface UserRepository extends JpaRepository<User, Long> { @Cacheable User findByName(String name); }
Hibernate: insert into user (age, name) values (?, ?) Hibernate: select user0_.id as id1_0_, user0_.age as age2_0_, user0_.name as name3_0_ from user user0_ where user0_.name=? 第一次查询:10 第二次查询:10
到这里,咱们能够看到,在调用第二次findByName函数时,没有再执行select语句,也就直接减小了一次数据库的读取操做。缓存
为了能够更好的观察,缓存的存储,咱们能够在单元测试中注入cacheManager。springboot
@Autowired private CacheManager cacheManager;
使用debug模式运行单元测试,观察cacheManager中的缓存集users以及其中的User对象的缓存加深理解。app
源码来源函数