实现分页查询的mybatis和mybatis-plus的代码分析
mybatis-plus实现分页查询
首先,本人是在STS使用springboot脚手架建立一个maven工程,配置的依赖如下:
yml的配置如下;
#server
server:
port: 80
servlet:
context-path: /
tomcat:
max-threads: 1000
#spring
spring:
datasource:
url: jdbc:mysql:///jtsys?serverTimezone=GMT%2B8&characterEncoding=utf8
username: root
password: root
thymeleaf:
prefix: classpath:/templates/pages/
suffix: .html
#mybatis
mybatis-plus:
configuration:
default-statement-timeout: 30
map-underscore-to-camel-case: true
mapper-locations:
- classpath:/mapper/*/*.xml
#log
logging:
level:
com.cy: DEBUG
最后:需要安装Lombok插件,找到导入的Lombok的jar包双击就弹出安装界面,再选择自动搜索出的STS软件中就可以
1.数据库准备
建立一个数据库test,再建立一个表Sys_roles
表Sys_roles数据代码如下:
/*
SQLyog 企业版 - MySQL GUI v8.14
MySQL - 5.5.27
*********************************************************************
*/
/*!40101 SET NAMES utf8 */;
create table `sys_roles` (
`id` double ,
`name` varchar (300),
`note` varchar (1500),
`createdTime` datetime ,
`modifiedTime` datetime ,
`createdUser` varchar (60),
`modifiedUser` varchar (60)
);
insert into `sys_roles` (`id`, `name`, `note`, `createdTime`, `modifiedTime`, `createdUser`, `modifiedUser`) values('47','超级管理员','负责系统所有模块的管理','2020-04-29 10:59:45','2020-05-09 16:22:24',NULL,NULL);
insert into `sys_roles` (`id`, `name`, `note`, `createdTime`, `modifiedTime`, `createdUser`, `modifiedUser`) values('48','初级软件工程师','负责代码实现','2020-04-29 11:02:01','2020-05-11 11:29:26',NULL,NULL);
insert into `sys_roles` (`id`, `name`, `note`, `createdTime`, `modifiedTime`, `createdUser`, `modifiedUser`) values('49','中级软件工程师','负责需求分析,模块设计','2020-04-29 16:05:58','2020-04-29 17:03:20',NULL,NULL);
2.pojo的准备
JsonResult 类–封装呈现到页面的数据。以及成功失败的状态信息,以及捕获的报错信息
package com.cy.pj.sys.pojo;
import java.io.Serializable;
import lombok.Data;
@Data
public class JsonResult implements Serializable {
private static final long serialVersionUID = 7816949974168795608L;
//状态码
private int state=1;//成功表示1,执行失败表示0
//状态信息
private String message="ok";
//正确数据
private Object data;
//写构造方法的目的吗是,在controller层直接new一个JsonRueslt来设置属性值
public JsonResult() {}
//如果执行失败new JsonResult对象可以获取抛出来的异常信息封装到message,并且告诉执行失败
public JsonResult(Throwable t){
this.state=0;
this.message=t.getMessage();
}
public JsonResult(String message) {
this.message=message;
}
public JsonResult(Object data) {
this.data=data;
}
}
SysRole–封装数据库字段的信息,传递数据库的数据
package com.cy.pj.sys.pojo;
import java.io.Serializable;
import java.util.Date;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@NoArgsConstructor
@AllArgsConstructor
@TableName("sys_roles")
@Data
public class SysRole implements Serializable {
private static final long serialVersionUID = 5013943989061127383L;
@TableId(type = IdType.AUTO)//自增
private Integer id;
private String name;
private String note;
@TableField("createdTime")
private Date createdTime;
@TableField("modifiedTime")
private Date modifiedTime;
@TableField("createdUser")
private String createdUser;
@TableField("modifiedUser")
private String modifiedUser;
}
4.定义全局异常拦截器
SystemExeAOP 类–目的是获取全局的异常传递到JsonResult类中,并且JsonResult类输出成一个JSON字符串,方便页面获取到数据信息
package com.cy.pj.sys.aop;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import com.cy.pj.sys.pojo.JsonResult;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@RestControllerAdvice //@RestControllerAdvice=@ControllerAdvice+@ResponseBody
public class SystemExeAOP {
@ExceptionHandler(RuntimeException.class)
public Object systemResultExcepton(Exception exception) {
exception.printStackTrace();
log.error("~~~~~~~+"+exception.getMessage()+"+",exception);
return new JsonResult(exception);
}
}
5.控制层的实现RoleController
package com.cy.pj.sys.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.cy.pj.sys.Service.SysRoleService;
import com.cy.pj.sys.pojo.JsonResult;
@RestController
@RequestMapping("/role/")
public class RoleController {
@Autowired
private SysRoleService sysRoleService;
/**
* 业务:查询按照用户名查询角色表的数据并按创建时间排序,同时实现分页查询
* equest URL:
* http://localhost/role/doFindPageObjects?pageCurrent=1&name=超级管理员&pageSize=10
*Request Method: GET
* 参数:pageCurrent=1
* name=admin
* pageSize=10
*返回结果:new JsonResult(List...)
*/
@RequestMapping("doFindPageObjects")
private JsonResult doFindPageObjects(String name,Integer pageCurrent,Integer pageSize) {
return new JsonResult(sysRoleService.findPageObjects(name,pageCurrent,pageSize));
}
}
6.服务层的实现RoleService和RoleServiceImpl
package com.cy.pj.sys.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.cy.pj.sys.pojo.SysRole;
public interface SysRoleService {
IPage<SysRole> findPageObjects(String name, Integer pageCurrent,Integer pageSize);
}
```java
package com.cy.pj.sys.Service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cy.pj.sys.Service.SysRoleService;
import com.cy.pj.sys.dao.SysRoleDao;
import com.cy.pj.sys.pojo.SysRole;
@Service
public class SysRoleServiceImpl implements SysRoleService {
@Autowired
private SysRoleDao sysRoleDao;
@Override
public IPage<SysRole> findPageObjects(String name, Integer pageCurrent,Integer pageSize) {
//PageObject<SysRole>因为我想将页面的pageCurrent(当前页码),pageSize(分页数),rowCount(总行数),pageCount(总页数),records(查询结果的集合List<SysRole>)
//1.定义分页对象
Page<SysRole> mpPage=new Page<>(pageCurrent, pageSize);
//2.定义条件构造器
QueryWrapper<SysRole> queryWrapper2 = new QueryWrapper<>();
//3.要求:按照更新时间,进行排序 降序排列.
queryWrapper2.eq("name", name)
.orderByDesc("createdTime")
;
IPage<SysRole> selectPage = sysRoleDao.selectPage(mpPage, queryWrapper2);
// long current = selectPage.getCurrent();//当前页
long total = selectPage.getTotal();//当前满足条件总行数
// long pages = selectPage.getPages();//分页总页数
// List<SysRole> records = selectPage.getRecords();//分页对象记录列表
if(total<=0)
throw new IllegalArgumentException("没有查询到对应的记录");
return selectPage;
}
}
7.持久层的实现SysRoleDao
package com.cy.pj.sys.dao;
import org.apache.ibatis.annotations.Mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.cy.pj.sys.pojo.SysRole;
@Mapper
public interface SysRoleDao extends BaseMapper<SysRole> {
}
8.mybatis-plus分页查询的分页拦截器的实现
最后一步,如果想Page<>起作用,需要创建一个mybatis-plus分页查询的分页拦截器
package com.cy.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/*
* 指示一个类声明一个或多个@Bean方法,并且可以由Spring容器在运行时为这些Bean生成Bean定义和服务请求
*/
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
@Configuration
public class MybatisPlusConfig {
@Bean//分页接受器(PaginationInterceptor)
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
9.查看结果
在浏览器输入: http://localhost/role/doFindPageObjects?pageCurrent=1&name=超级管理员&pageSize=10
得到以下结果:
目前,我只写了mybatis-plus的代码实现和分析,用mybatis实现主要通过xml映射文件来写SQL语句,而mybatis-plus的Page<>实现类世界城iPage接口的分页实现类,封装好分页的查询的SQL语句以及计算逻辑