1.首先创建springboot项目,添加依赖,依赖一定要跟springboot版本对应,否则会报错
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.30</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.30</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.6</version>
</dependency>
<!-- mybatis plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.5</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>3.0.3</version>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.0.2</version>
</dependency>
<!-- 常用工具类 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<!-- Swagger -->
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.6.12</version>
</dependency>
<!-- Jackson(JSON序列化) -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.38</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<version>5.0.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.16</version>
</dependency>
之前有写过springboot整合mybatis-plus的文章,可以去上一篇文章查看
配置好依赖后在application.xml中添加mybatis-plus和Redis的配置
spring:
application:
name: springBoot
servlet:
multipart:
enabled: true
max-file-size: 20MB
max-request-size: 20MB
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: Asia/Shanghai
datasource:
url: jdbc:mysql://localhost:3306/xxb?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8&zeroDateTimeBehavior=convertToNull
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
hikari:
# ???????
maximum-pool-size: 20
# ????????
minimum-idle: 10
# ?????????????
connectionTimeout: 30000
# ??????
validationTimeout: 5000
# ?????????????10??
idleTimeout: 600000
# ??????????????????0???????????30??
maxLifetime: 1800000
# ????query????????????
connectionTestQuery: SELECT 1
mybatis-plus:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.example.xxb.entity
checkConfigLocation: false
configuration:
# ?????????camel case???
mapUnderscoreToCamelCase: true
# MyBatis ??????
# NONE???? PARTIAL?????? resultMap ???? FULL???? resultMap ????
autoMappingBehavior: PARTIAL
# MyBatis ????????????????
# NONE????? WARNING??????? FAILING??????????
autoMappingUnknownColumnBehavior: NONE
# ???????? ?????? org.apache.ibatis.logging.stdout.StdOutImpl
# ?????? (????? p6spy ??) org.apache.ibatis.logging.nologging.NoLoggingImpl
# ?????? org.apache.ibatis.logging.slf4j.Slf4jImpl
logImpl: org.apache.ibatis.logging.stdout.StdOutImpl
--- # Redis配置
spring:
data:
redis:
host: 127.0.0.1
port: 6379
password: 123456
database: 0
timeout: 100s
lettuce:
pool:
enabled: true # 启用连接池
max-active: 8 # 最大活跃连接数
max-idle: 8 # 最大空闲连接数
min-idle: 2 # 最小空闲连接数
max-wait: 5000ms # 获取连接最大等待时间
shutdown-timeout: 100ms # 关闭超时时间
之后就可以开始编写代码了。
创建数据表和对应的实体类
@Data
@TableName("school")
public class School implements Serializable {
private int id;//ID自增
private String name; // 学校名称
private String grade; // 年级
private String className; // 班级
public School() {
}
}
@Data
@TableName("student")
public class Student implements Serializable {
private int id;
private String name;
private String grade; // 类型为String
private String className;
private Integer schoolId;
private Integer teacherId;
@TableField(exist = false)
private School school;
@TableField(exist = false)
private Teacher teacher;
public Student(){
}
}
@Data
@TableName("teacher")
public class Teacher implements Serializable {
private int id;//ID自增
private String name; // 老师姓名
private Integer schoolId; // 所在学校
private String grade; // 所在年级
private String className; // 所在班级
public Teacher() {}
}
再编写对应的Mapper,service跟controller
Mapper:
package com.example.springboot2.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.springboot2.entity.School;
import com.example.springboot2.entity.Teacher;
public interface SchoolMapper extends BaseMapper<School> {
}
package com.example.springboot2.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.springboot2.entity.Student;
import org.apache.ibatis.annotations.Select;
import com.example.springboot2.dto.StudentDetailsDTO;
public interface StudentMapper extends BaseMapper<Student> {
Student selectStudentWithDetails(Integer id);
}
package com.example.springboot2.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot2.dto.ClassInfoDTO;
import com.example.springboot2.entity.Result;
import com.example.springboot2.entity.School;
import com.example.springboot2.entity.Student;
import com.example.springboot2.entity.Teacher;
import com.example.springboot2.mapper.SchoolMapper;
import com.example.springboot2.mapper.StudentMapper;
import com.example.springboot2.mapper.TeacherMapper;
import com.example.springboot2.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/teachers")
public class TeacherController {
@Autowired
private TeacherService teacherService;
private final SchoolMapper schoolMapper;
private final StudentMapper studentMapper;
private final TeacherMapper teacherMapper;
public TeacherController(SchoolMapper schoolMapper, TeacherMapper teacherMapper,StudentMapper studentMapper) {
this.schoolMapper = schoolMapper;
this.teacherMapper = teacherMapper;
this.studentMapper = studentMapper;
}
@CacheEvict(value = "classInfoCache", allEntries = true)
@PostMapping("/teacher")
public String addTeacher(@RequestBody Teacher teacher) {
// 根据 schoolId 查询学校是否存在
School school = schoolMapper.selectById(teacher.getSchoolId());
if (school == null) {
throw new RuntimeException("学校不存在");
}
teacherMapper.insert(teacher);
return "教师添加成功";
}
// 删除教师
@DeleteMapping("/{id}")
public Result<Void> deleteTeacher(@PathVariable Integer id) {
teacherService.removeById(id);
return Result.success(null);
}
// 更新教师
@PutMapping("/{id}")
public Result<Void> updateTeacher(@PathVariable Integer id, @RequestBody Teacher teacher) {
teacher.setId(id);
teacherService.updateById(teacher);
return Result.success(null);
}
// 根据ID查询教师
@GetMapping("/{id}")
public Result<Teacher> getTeacherById(@PathVariable Integer id) {
Teacher teacher = teacherService.getById(id);
return Result.success(teacher);
}
// 分页查询所有教师
@GetMapping("/list")
public Result<Page<Teacher>> listTeachers(
@RequestParam(defaultValue = "1") Integer page,
@RequestParam(defaultValue = "10") Integer size) {
Page<Teacher> pageParam = new Page<>(page, size);
return Result.success(teacherService.pageTeachers(pageParam));
}
// 缓存班级信息到Redis
@Cacheable(value = "classInfoCache", key = "#schoolName + '-' + #grade + '-' + #className",unless = "#result == null")
@GetMapping("/class-info")
public ClassInfoDTO getClassInfo(
@RequestParam String schoolName,
@RequestParam String grade,
@RequestParam String className) {
// 查询学校ID
School school = schoolMapper.selectOne(new QueryWrapper<School>().eq("name", schoolName));
if (school == null) {
throw new RuntimeException("学校不存在");
}
// 查询学生
QueryWrapper<Student> studentWrapper = new QueryWrapper<>();
studentWrapper.eq("school_id", school.getId())
.eq("grade", grade)
.eq("class_name", className);
List<Student> students = studentMapper.selectList(studentWrapper);
// 查询教师
QueryWrapper<Teacher> teacherWrapper = new QueryWrapper<>();
teacherWrapper.eq("school_id", school.getId())
.eq("grade", grade)
.eq("class_name", className);
Teacher teacher = teacherMapper.selectOne(teacherWrapper);
// 封装DTO
ClassInfoDTO dto = new ClassInfoDTO();
dto.setSchoolName(schoolName);
dto.setGrade(grade);
dto.setClassName(className);
dto.setStudents(students);
dto.setTeacher(teacher);
return dto;
}
}
mapper.xml可以用deepseek生成
service:
package com.example.springboot2.service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.example.springboot2.entity.School;
public interface SchoolService extends IService<School> {
Page<School> pageSchools(Page<School> page);
}
package com.example.springboot2.service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot2.dto.StudentDetailsDTO;
import com.example.springboot2.entity.Student;
import com.example.springboot2.mapper.StudentMapper;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
@Service
public class StudentService {
private final StudentMapper studentMapper;
public StudentService(StudentMapper studentMapper) {
this.studentMapper = studentMapper;
}
@Cacheable(value = "studentCache", key = "#studentId")
public StudentDetailsDTO getStudentDetails(Integer studentId) {
// 查询学生详情(包含学校和老师)
Student student = studentMapper.selectStudentWithDetails(studentId);
if (student == null) {
throw new RuntimeException("学生不存在");
}
// 查询同班同学
QueryWrapper<Student> wrapper = new QueryWrapper<>();
wrapper.eq("grade", student.getGrade())
.eq("class_name", student.getClassName())
.ne("id", studentId); // 排除自己
List<Student> classmates = studentMapper.selectList(wrapper);
// 封装DTO
StudentDetailsDTO dto = new StudentDetailsDTO();
dto.setStudent(student);
dto.setClassmates(classmates);
return dto;
}
@Cacheable(value = "studentsPageCache", key = "#page.current + '-' + #page.size")
public Page<Student> page(Page<Student> page) {
return studentMapper.selectPage(page, null);
}
// 更新学生时清除缓存
@CacheEvict(value = {"studentCache", "studentsPageCache", "classInfoCache"}, allEntries = true)
public void updateStudent(Student student) {
studentMapper.updateById(student);
}
// 删除学生时清除缓存
@CacheEvict(value = {"studentCache", "studentsPageCache", "classInfoCache"}, allEntries = true)
public void deleteStudent(Integer id) {
studentMapper.deleteById(id);
}
}
package com.example.springboot2.service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.example.springboot2.entity.Teacher;
public interface TeacherService extends IService<Teacher> {
Page<Teacher> pageTeachers(Page<Teacher> page);
}
package com.example.springboot2.service.impl;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.springboot2.entity.School;
import com.example.springboot2.mapper.SchoolMapper;
import com.example.springboot2.service.SchoolService;
import org.springframework.stereotype.Service;
@Service
public class SchoolServiceImpl extends ServiceImpl<SchoolMapper, School> implements SchoolService {
@Override
public Page<School> pageSchools(Page<School> page) {
return baseMapper.selectPage(page, null);
}
}
package com.example.springboot2.service.impl;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.springboot2.entity.Teacher;
import com.example.springboot2.mapper.TeacherMapper;
import com.example.springboot2.service.TeacherService;
import org.springframework.stereotype.Service;
@Service
public class TeacherServiceImpl extends ServiceImpl<TeacherMapper, Teacher> implements TeacherService {
@Override
public Page<Teacher> pageTeachers(Page<Teacher> page) {
return baseMapper.selectPage(page, null);
}
}
Controller:
package com.example.springboot2.controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot2.entity.Result;
import com.example.springboot2.entity.School;
import com.example.springboot2.mapper.SchoolMapper;
import com.example.springboot2.service.SchoolService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/schools")
public class SchoolController {
@Autowired
private SchoolService schoolService;
private final SchoolMapper schoolMapper;
public SchoolController(SchoolMapper schoolMapper) {
this.schoolMapper = schoolMapper;
}
@CacheEvict(value = "classInfoCache", allEntries = true)
@PostMapping("/school")
public String addSchool(@RequestBody School school) {
if (school.getName() == null || school.getName().isEmpty()) {
throw new IllegalArgumentException("学校名称不能为空");
}
schoolMapper.insert(school);
return "学校添加成功";
}
// 删除学校
@DeleteMapping("/{id}")
public Result<Void> deleteSchool(@PathVariable Integer id) {
schoolService.removeById(id);
return Result.success(null);
}
// 更新学校
@PutMapping("/{id}")
public Result<Void> updateSchool(@PathVariable Integer id, @RequestBody School school) {
school.setId(id);
schoolService.updateById(school);
return Result.success(null);
}
// 根据ID查询学校
@GetMapping("/{id}")
public Result<School> getSchoolById(@PathVariable Integer id) {
School school = schoolService.getById(id);
return Result.success(school);
}
// 分页查询所有学校
@GetMapping("/list")
public Result<Page<School>> listSchools(
@RequestParam(defaultValue = "1") Integer page,
@RequestParam(defaultValue = "10") Integer size) {
Page<School> pageParam = new Page<>(page, size);
return Result.success(schoolService.pageSchools(pageParam));
}
}
package com.example.springboot2.controller;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot2.dto.ClassInfoDTO;
import com.example.springboot2.dto.StudentDetailsDTO;
import com.example.springboot2.entity.School;
import com.example.springboot2.entity.Student;
import com.example.springboot2.entity.Teacher;
import com.example.springboot2.mapper.SchoolMapper;
import com.example.springboot2.mapper.StudentMapper;
import com.example.springboot2.mapper.TeacherMapper;
import com.example.springboot2.service.StudentService;
import com.example.springboot2.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api")
public class StudentController {
@Autowired
private StudentService studentService;
private final StudentMapper studentMapper;
private final SchoolMapper schoolMapper;
private final TeacherMapper teacherMapper;
public StudentController(StudentMapper studentMapper, SchoolMapper schoolMapper,TeacherMapper teacherMapper) {
this.studentMapper = studentMapper;
this.schoolMapper = schoolMapper;
this.teacherMapper = teacherMapper;
}
@PostMapping("/student")
public String addStudent(@RequestBody Student student) {
if (student.getSchoolId() == null) {
throw new IllegalArgumentException("学校ID不能为空");
}
if (student.getTeacherId() == null) {
throw new IllegalArgumentException("教师ID不能为空");
}
// 查询学校和教师是否存在
School school = schoolMapper.selectById(student.getSchoolId());
Teacher teacher = teacherMapper.selectById(student.getTeacherId());
if (school == null || teacher == null) {
throw new RuntimeException("关联的学校或教师不存在");
}
studentMapper.insert(student);
return "学生添加成功";
}
//分页查询
@GetMapping("/students")
public Page<Student> getAllStudents(
@RequestParam(defaultValue = "1") Integer page,
@RequestParam(defaultValue = "10") Integer size) {
return studentService.page(new Page<>(page, size));
}
//根据ID查询
@GetMapping("/student/{id}")
public StudentDetailsDTO getStudentDetails(@PathVariable Integer id) {
return studentService.getStudentDetails(id);
}
//更新学生信息
@PutMapping("/student/{id}")
public String updateStudent(
@PathVariable Integer id,
@RequestBody Student student) {
student.setId(id);
studentMapper.updateById(student);
return "更新成功";
}
//删除学生
@DeleteMapping("/student/{id}")
public String deleteStudent(@PathVariable Integer id) {
studentMapper.deleteById(id);
return "删除成功";
}
//根据教师ID查询所有学生
@GetMapping("/teacher/{teacherId}/students")
public List<Student> getStudentsByTeacherId(@PathVariable Integer teacherId) {
QueryWrapper<Student> wrapper = new QueryWrapper<>();
wrapper.eq("teacher_id", teacherId);
return studentMapper.selectList(wrapper);
}
@Autowired
private RedisUtil redisUtil;
// @Cacheable(value = "classInfoCache", key = "#schoolName + '-' + #grade + '-' + #className")
@GetMapping("/class-info")
public Object getClassInfo(
@RequestParam String schoolName,
@RequestParam String grade,
@RequestParam String className) {
Object str= redisUtil.get("class-info:"+className);
if(str!=null){
JSONObject classInfoDTO = JSONUtil.parseObj(str);
return classInfoDTO;
}
// 查询学校ID
School school = schoolMapper.selectOne(new QueryWrapper<School>().eq("name", schoolName));
if (school == null) {
throw new RuntimeException("学校不存在");
}
// 查询学生:使用school_id作为条件
QueryWrapper<Student> studentWrapper = new QueryWrapper<>();
studentWrapper.eq("school_id", school.getId())
.eq("grade", grade)
.eq("class_name", className);
List<Student> students = studentMapper.selectList(studentWrapper);
// 查询教师:同样使用school_id
QueryWrapper<Teacher> teacherWrapper = new QueryWrapper<>();
teacherWrapper.eq("school_id", school.getId())
.eq("grade", grade)
.eq("class_name", className)
.last("LIMIT 1")
;
Teacher teacher = teacherMapper.selectOne(teacherWrapper);
ClassInfoDTO dto = new ClassInfoDTO();
dto.setSchoolName(schoolName);
dto.setGrade(grade);
dto.setClassName(className);
dto.setStudents(students);
dto.setTeacher(teacher);
redisUtil.set("class-info:"+className, JSONUtil.toJsonStr(dto),1000*60);
return dto;
}
}
package com.example.springboot2.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot2.dto.ClassInfoDTO;
import com.example.springboot2.entity.Result;
import com.example.springboot2.entity.School;
import com.example.springboot2.entity.Student;
import com.example.springboot2.entity.Teacher;
import com.example.springboot2.mapper.SchoolMapper;
import com.example.springboot2.mapper.StudentMapper;
import com.example.springboot2.mapper.TeacherMapper;
import com.example.springboot2.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/teachers")
public class TeacherController {
@Autowired
private TeacherService teacherService;
private final SchoolMapper schoolMapper;
private final StudentMapper studentMapper;
private final TeacherMapper teacherMapper;
public TeacherController(SchoolMapper schoolMapper, TeacherMapper teacherMapper,StudentMapper studentMapper) {
this.schoolMapper = schoolMapper;
this.teacherMapper = teacherMapper;
this.studentMapper = studentMapper;
}
@CacheEvict(value = "classInfoCache", allEntries = true)
@PostMapping("/teacher")
public String addTeacher(@RequestBody Teacher teacher) {
// 根据 schoolId 查询学校是否存在
School school = schoolMapper.selectById(teacher.getSchoolId());
if (school == null) {
throw new RuntimeException("学校不存在");
}
teacherMapper.insert(teacher);
return "教师添加成功";
}
// 删除教师
@DeleteMapping("/{id}")
public Result<Void> deleteTeacher(@PathVariable Integer id) {
teacherService.removeById(id);
return Result.success(null);
}
// 更新教师
@PutMapping("/{id}")
public Result<Void> updateTeacher(@PathVariable Integer id, @RequestBody Teacher teacher) {
teacher.setId(id);
teacherService.updateById(teacher);
return Result.success(null);
}
// 根据ID查询教师
@GetMapping("/{id}")
public Result<Teacher> getTeacherById(@PathVariable Integer id) {
Teacher teacher = teacherService.getById(id);
return Result.success(teacher);
}
// 分页查询所有教师
@GetMapping("/list")
public Result<Page<Teacher>> listTeachers(
@RequestParam(defaultValue = "1") Integer page,
@RequestParam(defaultValue = "10") Integer size) {
Page<Teacher> pageParam = new Page<>(page, size);
return Result.success(teacherService.pageTeachers(pageParam));
}
// 缓存班级信息到Redis
@Cacheable(value = "classInfoCache", key = "#schoolName + '-' + #grade + '-' + #className",unless = "#result == null")
@GetMapping("/class-info")
public ClassInfoDTO getClassInfo(
@RequestParam String schoolName,
@RequestParam String grade,
@RequestParam String className) {
// 查询学校ID
School school = schoolMapper.selectOne(new QueryWrapper<School>().eq("name", schoolName));
if (school == null) {
throw new RuntimeException("学校不存在");
}
// 查询学生
QueryWrapper<Student> studentWrapper = new QueryWrapper<>();
studentWrapper.eq("school_id", school.getId())
.eq("grade", grade)
.eq("class_name", className);
List<Student> students = studentMapper.selectList(studentWrapper);
// 查询教师
QueryWrapper<Teacher> teacherWrapper = new QueryWrapper<>();
teacherWrapper.eq("school_id", school.getId())
.eq("grade", grade)
.eq("class_name", className);
Teacher teacher = teacherMapper.selectOne(teacherWrapper);
// 封装DTO
ClassInfoDTO dto = new ClassInfoDTO();
dto.setSchoolName(schoolName);
dto.setGrade(grade);
dto.setClassName(className);
dto.setStudents(students);
dto.setTeacher(teacher);
return dto;
}
}
这样一个基本的springboot+mybatis-plus的增删改查就做完了,接着我们编写拦截器
拦截器:
package com.example.springboot2.config;
import com.example.springboot2.interceptor.AuthInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
//拦截器
@Configuration
public class WebConfig implements WebMvcConfigurer {
private final AuthInterceptor authInterceptor;
public WebConfig(AuthInterceptor authInterceptor) {
this.authInterceptor = authInterceptor;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(authInterceptor)
.addPathPatterns("/api/**") // 拦截所有/api开头的请求
.excludePathPatterns("/api/login"); // 排除登录接口
}
}
判断这个开头的请求有没有认证,有就放行,没有就报错
package com.example.springboot2.interceptor;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
@Slf4j
@Component
public class AuthInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
log.info("请求开始 => URI: {} | Method: {}", request.getRequestURI(), request.getMethod());
// 示例:简单的权限验证
String token = request.getHeader("Authorization");
if (token == null || !token.startsWith("Bearer ")) {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "缺少有效的认证信息");
return false;
}
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
log.info("请求处理完成 => URI: {}", request.getRequestURI());
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
Exception ex) throws Exception {
if (ex != null) {
log.error("请求异常 => URI: {} | Error: {}", request.getRequestURI(), ex.getMessage());
}
log.info("请求结束 => URI: {} | Status: {}", request.getRequestURI(), response.getStatus());
}
}
到这里拦截器就配置完了,然后我们开始自定义异常,在它报错的时候我们能够跟清楚地看到为什么报错
创建exception包,在这个包下创建我们的自定义异常类
package com.example.springboot2.exception;
public class BusinessException extends RuntimeException {
private int code;
public BusinessException(int code, String message) {
super(message);
this.code = code;
}
public int getCode() {
return code;
}
}
package com.example.springboot2.exception;
import com.example.springboot2.entity.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;
import java.net.SocketException;
import java.util.stream.Collectors;
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
// 处理业务异常
@ExceptionHandler(BusinessException.class)
public Result<Void> handleBusinessException(BusinessException e) {
log.error("业务异常: {}", e.getMessage(), e);
return Result.error(e.getCode(), e.getMessage());
}
// 处理数据库唯一键冲突
@ExceptionHandler(DuplicateKeyException.class)
public Result<Void> handleDuplicateKeyException(DuplicateKeyException e) {
log.error("唯一键冲突: {}", e.getMessage(), e);
return Result.error(500, "数据已存在,请勿重复提交");
}
// 处理参数校验异常
@ExceptionHandler(MethodArgumentNotValidException.class)
public Result<Void> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
BindingResult bindingResult = e.getBindingResult();
String errorMsg = bindingResult.getFieldErrors().stream()
.map(fieldError -> fieldError.getField() + ": " + fieldError.getDefaultMessage())
.collect(Collectors.joining("; "));
log.error("参数校验失败: {}", errorMsg);
return Result.error(400, errorMsg);
}
// 处理其他所有异常
@ExceptionHandler(Exception.class)
public Result<Void> handleException(Exception e) {
log.error("系统异常: {}", e.getMessage(), e);
return Result.error(500, "系统繁忙,请稍后再试");
}
// 处理404异常(需在配置中启用)
@ExceptionHandler(NoHandlerFoundException.class)
public Result<Void> handleNoHandlerFoundException(NoHandlerFoundException e) {
log.error("接口不存在: {}", e.getRequestURL());
return Result.error(404, "接口不存在");
}
@ExceptionHandler(NullPointerException.class)
public Result<Void> handleNullPointerException(NullPointerException e) {
log.error("空指针异常: {}", e.getMessage(), e);
return Result.error(400, "请求参数存在空值"); // 自定义错误码和消息
}
@ExceptionHandler(SocketException.class)
public Result<Void> handleSocketException(SocketException e) {
log.error("网络连接异常: {}", e.getMessage(), e);
return Result.error(500, "网络连接异常,请检查网络设置");
}
}
package com.example.springboot2.exception;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
// GradeTypeHandler.java
@MappedTypes(String.class)
public class GradeTypeHandler extends BaseTypeHandler<String> {
@Override
public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
ps.setString(i, parameter);
}
@Override
public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
return rs.getString(columnName);
}
@Override
public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
return rs.getString(columnIndex);
}
@Override
public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
return cs.getString(columnIndex);
}
}
依赖都在上方,这里就不再赘述了,将上方的依赖全部添加到pom.xml文件就行,版本一定要对应
将代码运行后在Apifox或potman进行测试,报错时就会在控制台显示哪里出错
最后再添加Redis跟定时任务
编写Redis实体类:
@Data
@NoArgsConstructor
public class Result<T> implements Serializable {
private int code;
private String message;
private T data;
private long timestamp = System.currentTimeMillis();
// 手动编写全参构造函数(替代Lombok的@AllArgsConstructor)
public Result(int code, String message, T data) {
this.code = code;
this.message = message;
this.data = data;
}
// 成功方法:明确泛型类型
public static <T> Result<T> success(T data) {
return new Result<>(200, "成功", data);
}
// 错误方法:显式指定Result<Void>
public static Result<Void> error(int code, String message) {
return new Result<>(code, message, null); // 确保构造函数匹配
}
}
编写RedisConfig类跟Redisutil类:
package com.example.springboot2.config;
import io.lettuce.core.ClientOptions;
import io.lettuce.core.SocketOptions;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.time.Duration;
/**
* Redis 配置类,用于配置连接工厂、序列化方式及缓存管理。
*/
@Configuration
public class RedisConfig {
/**
* 配置 Lettuce 连接工厂。
* @return LettuceConnectionFactory 实例,包含连接参数和服务器配置。
*/
@Bean
public LettuceConnectionFactory redisConnectionFactory() {
// 客户端选项:自动重连、保持长连接
ClientOptions clientOptions = ClientOptions.builder()
.autoReconnect(true)
.socketOptions(SocketOptions.builder().keepAlive(true).build())
.build();
// Lettuce 客户端配置:超时时间为 30 秒
LettuceClientConfiguration clientConfig = LettuceClientConfiguration.builder()
.commandTimeout(Duration.ofSeconds(30))
.clientOptions(clientOptions)
.build();
// Redis 单节点配置:本地服务器,端口 6379,密码 123456
RedisStandaloneConfiguration serverConfig = new RedisStandaloneConfiguration();
serverConfig.setHostName("127.0.0.1");
serverConfig.setPort(6379);
serverConfig.setPassword("123456");
serverConfig.setDatabase(0);
return new LettuceConnectionFactory(serverConfig, clientConfig);
}
/**
* 配置 RedisTemplate,支持 JSON 序列化。
* @param factory Redis 连接工厂
* @return 配置后的 RedisTemplate 实例
*/
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
template.setEnableTransactionSupport(true); // 启用事务支持
// Key 使用字符串序列化,Value 使用 JSON 序列化
template.setKeySerializer(new StringRedisSerializer());
GenericJackson2JsonRedisSerializer serializer = new GenericJackson2JsonRedisSerializer();
template.setValueSerializer(serializer);
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(serializer);
template.afterPropertiesSet();
return template;
}
/**
* 配置默认缓存设置:JSON 序列化、30 分钟过期、不缓存空值。
*/
@Bean
public RedisCacheConfiguration cacheConfiguration() {
return RedisCacheConfiguration.defaultCacheConfig()
.serializeValuesWith(
RedisSerializationContext.SerializationPair.fromSerializer(
new GenericJackson2JsonRedisSerializer()
)
)
.entryTtl(Duration.ofMinutes(30))
.disableCachingNullValues();
}
/**
* 配置缓存管理器,设置统一的缓存过期时间。
* @param connectionFactory Redis 连接工厂
* @return RedisCacheManager 实例
*/
@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.serializeValuesWith(
RedisSerializationContext.SerializationPair.fromSerializer(
new GenericJackson2JsonRedisSerializer()
)
)
.entryTtl(Duration.ofMinutes(30));
return RedisCacheManager.builder(connectionFactory)
.cacheDefaults(config)
.transactionAware() // 支持事务
.build();
}
}
package com.example.springboot2.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
@Component
public class RedisUtil {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
// ============================String=============================
/**
* 普通缓存获取
*
* @param key 键
* @return 值
*/
public Object get(String key) {
return key == null ? null : redisTemplate.opsForValue().get(key);
}
/**
* 普通缓存放入
*
* @param key 键
* @param value 值
* @return true成功 false失败
*/
public boolean set(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 普通缓存放入并设置时间
*
* @param key 键
* @param value 值
* @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
* @return true成功 false 失败
*/
public boolean set(String key, Object value, long time) {
try {
if (time > 0) {
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
} else {
set(key, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
最后在studentcontroller类中调用
@Autowired
private RedisUtil redisUtil;
// @Cacheable(value = "classInfoCache", key = "#schoolName + '-' + #grade + '-' + #className")
@GetMapping("/class-info")
public Object getClassInfo(
@RequestParam String schoolName,
@RequestParam String grade,
@RequestParam String className) {
Object str= redisUtil.get("class-info:"+className);
if(str!=null){
JSONObject classInfoDTO = JSONUtil.parseObj(str);
return classInfoDTO;
}
// 查询学校ID
School school = schoolMapper.selectOne(new QueryWrapper<School>().eq("name", schoolName));
if (school == null) {
throw new RuntimeException("学校不存在");
}
// 查询学生:使用school_id作为条件
QueryWrapper<Student> studentWrapper = new QueryWrapper<>();
studentWrapper.eq("school_id", school.getId())
.eq("grade", grade)
.eq("class_name", className);
List<Student> students = studentMapper.selectList(studentWrapper);
// 查询教师:同样使用school_id
QueryWrapper<Teacher> teacherWrapper = new QueryWrapper<>();
teacherWrapper.eq("school_id", school.getId())
.eq("grade", grade)
.eq("class_name", className)
.last("LIMIT 1")
;
Teacher teacher = teacherMapper.selectOne(teacherWrapper);
ClassInfoDTO dto = new ClassInfoDTO();
dto.setSchoolName(schoolName);
dto.setGrade(grade);
dto.setClassName(className);
dto.setStudents(students);
dto.setTeacher(teacher);
redisUtil.set("class-info:"+className, JSONUtil.toJsonStr(dto),1000*60);
return dto;
}
运行代码进行测试,查看是否存入到Redis。
定时任务:
编写scheduiedtask类:
package com.example.springboot2.task;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
@Slf4j
@Component
@EnableAsync
public class ScheduledTasks {
@Value("${scheduled.reportInterval:300000}") // 默认5分钟
private long reportInterval;
@Value("${scheduled.dailyCleanupCron:0 0 0 * * ?}") // 默认每天凌晨执行
private String dailyCleanupCron;
/**
* 定期报告缓存状态并执行清理
* fixedRate: 执行间隔时间(毫秒),从配置文件读取,默认5分钟
* 异步执行避免阻塞其他任务
*/
@Async
@Scheduled(fixedRateString = "${scheduled.reportInterval:300000}")
public void reportCacheStatus() {
long startTime = System.currentTimeMillis();
log.info("[缓存维护] 任务启动 - 开始时间: {}", startTime);
try {
// 示例业务逻辑:清理过期缓存
int cleanedEntries = cleanExpiredCache();
log.info("[缓存维护] 已清理过期缓存条目: {}", cleanedEntries);
// 示例业务逻辑:缓存命中率统计
logCacheHitRate();
} catch (Exception e) {
log.error("[缓存维护] 任务执行异常", e);
} finally {
long cost = System.currentTimeMillis() - startTime;
log.info("[缓存维护] 任务完成 - 耗时: {}ms", cost);
}
}
/**
* 每日清理任务
* cron表达式从配置文件读取,默认每天0点执行
* 格式: 秒 分 时 日 月 周
*/
@Scheduled(cron = "${scheduled.dailyCleanupCron:0 0 0 * * ?}")
public void dailyCleanup() {
log.info("[每日清理] 任务启动");
try {
// 示例业务逻辑:清理临时文件
int deletedFiles = deleteTempFiles();
log.info("[每日清理] 已删除临时文件: {} 个", deletedFiles);
// 示例业务逻辑:数据库归档
archiveDatabase();
} catch (Exception e) {
log.error("[每日清理] 任务执行异常", e);
}
log.info("[每日清理] 任务完成");
}
// 示例方法:清理过期缓存(需实现具体逻辑)
private int cleanExpiredCache() {
// 实际实现应访问缓存服务
return (int) (Math.random() * 10); // 模拟返回值
}
// 示例方法:记录缓存命中率
private void logCacheHitRate() {
// 实际实现应收集缓存统计信息
double hitRate = Math.random() * 100;
log.info("[缓存统计] 当前命中率: {:.2f}%", hitRate);
}
// 示例方法:删除临时文件
private int deleteTempFiles() {
// 实际实现应操作文件系统
return (int) (Math.random() * 50); // 模拟返回值
}
// 示例方法:数据库归档
private void archiveDatabase() {
try {
// 模拟耗时操作
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
webconfig类:
package com.example.springboot2.config;
import com.example.springboot2.interceptor.AuthInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
//拦截器
@Configuration
public class WebConfig implements WebMvcConfigurer {
private final AuthInterceptor authInterceptor;
public WebConfig(AuthInterceptor authInterceptor) {
this.authInterceptor = authInterceptor;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(authInterceptor)
.addPathPatterns("/api/**") // 拦截所有/api开头的请求
.excludePathPatterns("/api/login"); // 排除登录接口
}
}
进行测试。
最后代码可以复制到deepseek进行符合自己框架版本的优化。