-
application.properties
文件中新增spring.jpa.properties.hibernate.show_sql=true
,开启hibernate对sql语句的打印 -
修改单元测试
ApplicationTests
,初始化插入User表一条用户名为AAA,年龄为10的数据。并通过findByName函数完成两次查询。
@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依赖,添加如下内容:
org.springframework.boot
spring-boot-starter-cache
- 在Spring Boot