- 配置文件:application.properties, 当然,也可以用 application.yml.
spring.datasource.url=jdbc:mysql://192.168.155.60:3306/cache
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# 启用 MyBatis 的驼峰命名法
mybatis.configuration.map-underscore-to-camel-case=true
# 打印 sql 日志
logging.level.com.fly.springbootcache.mapper=debug
- 新建实体类 Employee.java. 声明属性及
getter
and setter
方法。
- 建立
Mapper
接口,并标注 @Mapper
注解, 或者可以在 Springboot
启动类直接标注 @MapperScan("com.xxx")
来进行扫描 mapper。
并用 @EnableCaching
注解来开启缓存。
// 扫描 mapper 接口
@MapperScan(value = "com.fly.springbootcache.mapper")
@EnableCaching // 开启缓存
@SpringBootApplication
public class SpringBootCacheApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootCacheApplication.class, args);
}
}
- 在
EmployeeMapper.java
接口中添加一个查询方法
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Select;
import org.springframework.cache.annotation.Cacheable;
public interface EmployeeMapper {
@Options(useGeneratedKeys = true) // 使用自增主键
@Insert("INSERT INTO employee(lastName, email, gender, d_id)
values(#{lastName}, #{email}, #{gender}, #{dId})")
public void insert(Employee employee);
@Select("SELECT * FROM employee WHERE id = #{id}")
public Employee getById(Integer id);
}
- 添加
Service
类,并添加相应的查询方法,并在方法上面使用注解 @Cacheable
将查找到的结果加入缓存中, 当然,该注解也可以放在 Mapper
层。
@Service
public class EmployeeService {
@Autowired
private EmployeeMapper employeeMapper;
@Cacheable(cacheNames = "emp") //指定缓存的名字。 默认使用传入的参数作为 key, 即 id。
public Employee getById(Integer id) {
return employeeMapper.getById(id);
}
public Employee insert(Employee employee) {
employeeMapper.insert(employee);
return employee;
}
}
- 建立一个
controller
@RestController
public class EmployeeController {
@Autowired
private EmployeeService employeeService;
@GetMapping("/emp")
public Employee insert(Employee employee) {
return employeeService.insert(employee);
}
@GetMapping("/emp/{id}")
public Employee getById(@PathVariable("id") Integer id) {
return employeeService.getById(id);
}
}
- 启动应用, 在浏览器输入访问路径查看控制台打印的sql, 第一次查询是会打印出sql,第二次查询是不打印sql, 说明第二次直接查询的缓存,而不是查询的数据库。