Mybatis-Plus 多表实现分页(注解方式)
1、准备阶段
-
构建一个Springboot项目
-
引入需要依赖
<!--springWeb--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>2.7.6</version> </dependency> <!--mybatis-plus--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.5.1</version> </dependency> <!--mysql--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.26</version> </dependency>
-
创建数据表
student:学生表
student_class:班级表
-
配置 Mybatis-plus 分页插件
@Configuration public class MybatisConfig { /** * 分页插件 * @return */ @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); return interceptor; } }
-
配置全局返回类
public class R extends HashMap<String, Object> { /** * 状态码 */ public static final String CODE_TAG = "code"; /** * 返回内容 */ public static final String MSG_TAG = "msg"; /** * 数据对象 */ public static final String DATA_TAG = "data"; public R() { } public R(Integer code, String msg, Object data) { super.put(CODE_TAG, code); super.put(MSG_TAG, msg); if (data != null) { super.put(DATA_TAG, data); } } public static R ok() { return R.ok(200, "操作成功"); } public static R ok(Integer code, String msg) { return new R(code, msg, null); } public static R error() { return R.ok(500, "系统错误"); } public static R error(Integer code, String msg) { return new R(code, msg, null); } public static R ok(Object data) { return new R(200, "操作成功", data); } }
-
配置 application.yml
server: port: 8888 spring: datasource: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/test?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&autoReconnect=true username: root password: 123456 logging: level: com: zhang: debug
2、开始实现
(1)、单表分页
实体类
@TableName("student")
public class Student implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
/**
* 学生名称
*/
private String name;
/**
* 年龄
*/
private Integer age;
/**
* 班级id
*/
private Integer classId;
// ... get set 方法
}
Controller 层
@RestController
@RequestMapping("/student")
public class StudentController {
@Autowired
private IStudentService studentService;
@GetMapping("/list")
public R selectList() {
return R.ok(studentService.selectList());
}
}
Service 层
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements IStudentService {
public Object selectList() {
return this.baseMapper.selectPage(new Page<Student>(1, 10), null);
}
}
Mapper 层
public interface StudentMapper extends BaseMapper<Student> {
}
测试:
(2) 多表查询
编写Vo类,用于传输请求参数和返回参数
请求参数Vo类
public class RequestStudentVo {
// 学生名称
private String name;
// 开始年龄
private Integer startAge;
// 结束年龄
private Integer endAge;
// 班级名称
private String className;
private Integer page;
private Integer pageSize;
// ... get set方法
}
返回数据 Vo类
public class ResponseStudentVo {
private Integer id;
private String name;
private Integer age;
private String className;
// ... get set方法
}
Controller 层
@RestController
@RequestMapping("/student")
public class StudentController {
@Autowired
private IStudentService studentService;
@GetMapping("/list")
public R selectList() {
return R.ok(studentService.selectList());
}
@GetMapping("/selectPage")
public R selectStudentPage(RequestStudentVo vo){
return R.ok(studentService.selectStudentPage(vo));
}
}
Servicet 层
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements IStudentService {
@Autowired
private StudentMapper studentMapper;
public Object selectList() {
return this.baseMapper.selectPage(new Page<Student>(1, 10), null);
}
public Object selectStudentPage(RequestStudentVo vo) {
QueryWrapper<ResponseStudentVo> warpper = getWarpper(vo);
IPage<ResponseStudentVo> page = getPage(vo);
IPage<ResponseStudentVo> pageList = studentMapper.selectStudentPage(page, warpper);
return pageList;
}
/**
* 构建分页
*
* @param vo
* @param <T>
* @return
*/
private <T> IPage<T> getPage(RequestStudentVo vo) {
Integer page = vo.getPage() == null || vo.getPage() < 0 || vo.getPage() > 1000 ? 1 : vo.getPage();
Integer pageSize = vo.getPageSize() == null || vo.getPageSize() < 0 || vo.getPageSize() > 1000 ? 1 : vo.getPageSize();
return new Page<T>(page, pageSize);
}
/**
* 构建 warpper
*
* @param vo
* @param <T>
* @return
*/
private <T> QueryWrapper<T> getWarpper(RequestStudentVo vo) {
QueryWrapper<T> queryWrapper = new QueryWrapper<T>();
if (!StringUtils.isEmpty(vo.getName())) {
queryWrapper.like("s.name", vo.getName());
}
if (!ObjectUtils.isEmpty(vo.getStartAge()) && !ObjectUtils.isEmpty(vo.getEndAge())) {
queryWrapper.between("s.age", vo.getStartAge(), vo.getEndAge());
}
if (!ObjectUtils.isEmpty(vo.getClassName())) {
queryWrapper.like("ss.class_name", vo.getClassName());
}
return queryWrapper;
}
}
Mapper 层
public interface StudentMapper extends BaseMapper<Student> {
@Select("select s.id,s.`name`,s.age,ss.class_name from student s\n" +
"INNER JOIN student_class ss\n" +
"ON ss.id = s.class_id ${ew.customSqlSegment}")
IPage<ResponseStudentVo> selectStudentPage(IPage<ResponseStudentVo> page, @Param(Constants.WRAPPER) QueryWrapper<ResponseStudentVo> warpper);
}
说明:
${ew.customSqlSegment}:拼接 where 后的语句(在动态sql中请勿处于 标签内)
${ew.sqlSelect} :拼接 select SQL 主体
${ew.sqlSet} :拼接 update 主体
${ew.sqlSegment} : 拼接 where 后的语句
Mysql 原始sql:
select s.id,s.`name`,s.age,ss.class_name from student s
INNER JOIN student_class ss
ON ss.id = s.class_id
where s.name like '%李%'
and s.age BETWEEN 11 and 20
and ss.class_name like '%二%'
测试:
日志查看:
: ==> Preparing: select s.id,s.`name`,s.age,ss.class_name from student s INNER JOIN student_class ss ON ss.id = s.class_id WHERE (s.name LIKE ? AND s.age BETWEEN ? AND ? AND ss.class_name LIKE ?)
: ==> Parameters: %李%(String), 11(Integer), 20(Integer), %二%
: <== Total: 1