一:缓存
1.导入需要依赖
core:Cache
web:web
Sql:mysql+Mybatis
2.搭建基本环境
创建数据库
Student(学生表)
id int 主键:自增
name varchar(20) 姓名
gender bit 性别(true:女 false:男)
grade_id int 外键(年级编号)
Grade(年级表)
id int 主键:自增
name varchar(20) 年级名次
3.创建javaBean(POJO)
@Data
public class Student {
private Integer id;
private String name;
private Boolean gender;
private Integer gradeId;
}
@Data
public class Grade {
private Integer id;
private String name;
}
4.整和mybatis
4.1 application.properties
#dataSource
#spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis
spring.datasource.username=root
spring.datasource.password=root
#mybatis配置(开启驼峰命名)
mybatis.configuration.map-underscore-to-camel-case=true
4.2 mapper层编码
@Mapper
public interface StudentMapper {
/**
* 根据id获取到对象
* @param id 学生编号
* @return 学生对象
*/
@Select("select * from student where id=#{id}")
Student getStudentById(Integer id);
}
5.编码controller
@RestController
public class StudentContorller {
@Autowired
private StudentMapper studentMapper;
@RequestMapping("/getById/{stuid}")
public Student getById(@PathVariable("stuid") int stuid){
return studentMapper.getStudentById(stuid);
}
}
6.缓存
6.1缓存所需要的注解--开启应用缓存
/*
将数据放入到缓存中
cacheNames/value:指定缓存组件的名字
key:缓存数据使用的key,默认参数是方法的返回值
#root.methodName 被调用的方法名
#root.method.name 当前被调用的方法
#root.target 被调用的目标对象
#root.targetClass 被大哦有那个的目标对象类
#root.args[0] 被调用的方法的参数列表
keyGenerator:key的生成器,默认是主键id(和key是二选一)
cacheManager:指定缓存管理器(比如redis)
*/
@Cacheable(cacheNames="stu",key = "#root.args[0]")
@Override
public Student getStudentById(Integer stuid) {
return studentMapper.getStudentById(stuid);
}
6.2修改缓存中数据
@CachePut
6.3清楚缓存
@CacheEvict