一、创建工程
二、执行sql脚本
/*
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for department
-- ----------------------------
DROP TABLE IF EXISTS `department`;
CREATE TABLE `department` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`departmentName` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for employee
-- ----------------------------
DROP TABLE IF EXISTS `employee`;
CREATE TABLE `employee` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`lastName` varchar(255) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`gender` int(2) DEFAULT NULL,
`d_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
三、创建JavaBean
Department
package com.example.springbootcache.bean;
public class Department {
private Integer id;
private String departmentName;
public Department() {
super();
// TODO Auto-generated constructor stub
}
public Department(Integer id, String departmentName) {
super();
this.id = id;
this.departmentName = departmentName;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getDepartmentName() {
return departmentName;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
@Override
public String toString() {
return "Department [id=" + id + ", departmentName=" + departmentName + "]";
}
}
Employee
package com.example.springbootcache.bean;
public class Department {
private Integer id;
private String departmentName;
public Department() {
super();
// TODO Auto-generated constructor stub
}
public Department(Integer id, String departmentName) {
super();
this.id = id;
this.departmentName = departmentName;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getDepartmentName() {
return departmentName;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
@Override
public String toString() {
return "Department [id=" + id + ", departmentName=" + departmentName + "]";
}
}
四、整合MyBatis操作数据库
1、配置数据源(联向哪个数据库的)
spring.datasource.url=jdbc:mysql://192.168.50.36:3307/spring_cache
spring.datasource.username=root
spring.datasource.password=123456
# mysql.cj.jdbc报红可以将mysql依赖的runtime去掉
#下面这个其实可以不用配,会自己判断
#spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#设置驼峰命名法,因为实体类是dId,数据库是i_id没有对应,不设置则查不到dId
mybatis.configuration.map-underscore-to-camel-case=true
#显示查询的sql语句
logging.level.com.example.springbootcache.mapper=debug
2、使用注解版的MyBatis
1)@MapperScan指定需要扫描mapper接口所在的包
2)编写mapper接口
EmployeeMapper
package com.example.springbootcache.mapper;
import com.example.springbootcache.bean.Employee;
import org.apache.ibatis.annotations.*;
@Mapper
@Repository
public interface EmployeeMapper {
@Select("SELECT * FROM employee WHERE id = #{id}")
public Employee getEmpById(Integer id);
//d_id是数据库中的,dId是对应实体类中的
@Update("UPDATE Employee SET lastName=#{lastName},email=#{email},gender=#{gender},d_id=#{dId} WHERE id=#{id}")
public void updateEmp(Employee employee);
@Delete("DELETE FROM employee WHERE id=#{id}")
public void deleteEmpByid(Integer id);
@Insert("INSERT INTO employee(lastName,email,gender,d_id)VALUES(#{lastName},#{email},#{gender},#{dId})")
public void insertEmp(Employee employee);
}
3)编写service
package com.example.springbootcache.service;
import com.example.springbootcache.bean.Employee;
import com.example.springbootcache.mapper.EmployeeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class EmployeeService {
@Autowired
EmployeeMapper employeeMapper;
public Employee getEmpById(Integer id) {
return employeeMapper.getEmpById(id);
}
}
4)编写controller
package com.example.springbootcache.controller;
import com.example.springbootcache.bean.Employee;
import com.example.springbootcache.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class EmployeeController {
@Autowired
EmployeeService employeeService;
@GetMapping("/emp/{id}")
public Employee getEmpById(@PathVariable("id")Integer id) {
Employee emp = employeeService.getEmpById(id);
return emp;
}
}
五、快速体验缓存
1、开启基于注解的缓存@EnableCaching
2、标注缓存注解即可
@Catchable
@Catchevict
@Catchput
上面的图说明没有缓存的,每次访问都会执行方法查询数据也就是查询员工会打印多次,加入缓存,不管访问几次都只会打印一次
六、测试
package com.example.springbootcache.service;
import com.example.springbootcache.bean.Employee;
import com.example.springbootcache.mapper.EmployeeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class EmployeeService {
@Autowired
EmployeeMapper employeeMapper;
/**
* 将方法的运行结果进行缓存,以后要相同的数据直接从缓存中获取,不用调用方法了
*
* CatcheManager管理多个Catch组件的,对缓存的真正CRUD操作在Catche组件中,每个缓存组件有自己唯一 一个名字
* 几个属性:
* catcheNames/value:指定缓存名字
* key:缓存数据使用的key;可以用它来设定(缓存是以键值对存放的)。默认就使用参数值
* 比如:id=1 则 key:value 为 1:Employee
* 可以编写SpEl #id(参数id的值) #a0 #p0 #root.args[0](取出参数列表的第一个参数)
* keyGenerator:key的生成器;可以自己指定key的生成器的组件id
* key/keyGenerator 二选一使用
* cacheManager:指定缓存管理器 或者cacheResolver指定缓存解析器 这两个也是二选一
* condition:符合条件的情况下才缓存 condition="#id>0"(当参数id的值大于0才缓存)
* unless:否定缓存 当unless指定的条件为true,方法的返回值就不被缓存
* 比如unless="#result==null" 返回的结果为空就不缓存 #result就是返回值,即存进缓存的结果
* sync:是否使用异步模式
* @param id
* @return
*/
@Cacheable(cacheNames = "emp")//这里的key=id
public Employee getEmpById(Integer id) {
System.out.println("查询员工");
return employeeMapper.getEmpById(id);
}
/**
* @CachePut 修改数据库中的某个参数,同时更新缓存
* 运行时机
* 1、先调用目标方法
* 2、将目标方法的结果缓存
*
* @param employee
* @return
* 在执行更新前,我们先查询emp,然后更新
* 这里要注意一个细节:在查询的时候会把id:Empolyee放进emp缓存
* 在更新的时候,我们是根据key的值来的,key值如果设置的不一样,就不会把原来的值给覆盖掉,而是将这个新的key:value存进缓存
*
* @Cacheable 中的key不可以用"#result",因为在获取key的时候方法还没运行,就没有返回值
*/
@CachePut(value = "emp",key = "#employee.id")//将结果也放在emp这个缓存中,这里的key的值要和传进来的id一样
public Employee updateEmp(Employee employee) {
System.out.println("updateEmp方法调用:"+employee);
employeeMapper.updateEmp(employee);
return employee;
}
}