创建SpringBoot工程
创建如下类:
@Entity
public class User {
@Id
@GeneratedValue
private long id;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private Integer age;
......省略getter和setter方法
}
jpa查询接口
public interface UserRepository extends JpaRepository<User,Long> {
User findByNameAndAge(String name, Integer age);
@Query("from User u where u.name=:name")
User findUser(@Param("name") String name);
@Cacheable
User findByName(String name);
}
application.yml配置
spring:
datasource:
url: jdbc:mysql://localhost:3306/test
username: root
password: ******
driver-class-name: com.mysql.jdbc.Driver
jpa:
hibernate:
ddl-auto: update
show-sql: true
Test测试类
@Autowired
private UserRepository userRepository;
@Before
public void before() {
userRepository.save(new User("BBB", 20));
}
@Test
public void test() throws Exception {
User user1 = userRepository.findByName("BBB");
System.out.println("第一次查询:" + user1.getAge());
User user2 = userRepository.findByName("BBB");
System.out.println("第二次查询:" + user2.getAge());
}
运行结果图
引入EhCache缓存依赖包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
在入口程序加入@EnableCaching注解
@SpringBootApplication
@EnableCaching
public class SpringbootCacheApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootCacheApplication.class, args);
}
}
数据接口中加入缓存注解
@CacheConfig(cacheNames = "user")
public interface UserRepository extends JpaRepository<User,Long> {
@Cacheable
User findByName(String name);
}
测试结果
注解含义:
@CacheConfig(cacheNames =”user”)将共用的查询结果放在user对象中
@Cacheable 配置了findByName函数的返回值将被加入缓存。同时在查询时,会先从缓存中获取,若不存在才再发起对数据库的访问
具体参考:(http://docs.spring.io/spring/docs/current/spring-framework-reference/html/cache.html)
(http://blog.didispace.com/springbootcache1)