Springboot+Mybatis-plus分页查询(单表+多表)

在这里插入图片描述

两张表 xu_student 学生表,xu_major 专业表

下面是建表语句

CREATE TABLE `xu_student` (                                                                                                                                                                                                                                                                                                                                      
              `id` VARCHAR(20) NOT NULL COMMENT 'id',                                                                                                                                                                                                                                                                                                
              `name` VARCHAR(55) DEFAULT NULL COMMENT '姓名',                                                                                                                                                                                                                                                                                                              
              `age` INT(11) DEFAULT NULL COMMENT '年龄',                                                                                                                                                                                                                                                                                                                   
              `email` VARCHAR(55) DEFAULT NULL COMMENT '邮箱',                                                                                                                                                                                                                                                                                                             
              `m_id` INT(20) DEFAULT NULL COMMENT '班级',                                                                                                                                                                                                                                                                                                                  
              PRIMARY KEY (`id`)                                                                                                                                                                                                                                                                                                                                             
            ) ENGINE=INNODB DEFAULT CHARSET=utf8`xu_student1`

在这里插入图片描述

CREATE TABLE `xu_major` (                                                                                                                                                                  
            `id` int(11) NOT NULL COMMENT '专业id',                                                                                                                                                
            `name` varchar(50) DEFAULT NULL COMMENT '专业名称',                                                                                                                                  
            PRIMARY KEY (`id`)                                                                                                                                                                       
          ) ENGINE=InnoDB DEFAULT CHARSET=utf8

在这里插入图片描述
(数据自己填)
项目目录
在这里插入图片描述

Student.class 实体类

@Data   //lombok简化代码,省去get,set方法
@TableName("xu_student")
public class Student implements Serializable {
    @TableId
    private String id;
    private String name;
    private Integer age;
    private String email;
    private Integer mId;
    
}

Major.class 实体类

@Data
@TableName("xu_major")
public class Major implements Serializable {
    @TableId
    private Integer Id;
    private String name;
}

单表分页

首先要一个mybatis-plus的分页插件
MybatisPlusConfig.class

package com.mp.configuration;

import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * mybatisPlus分页配置类
 */
@EnableTransactionManagement
@Configuration
@MapperScan("com.mp.dao")
public class MybatisPlusConfig {
    /**
     * druid注入
     * @return dataSource
     */
    @Bean(name = "dataSource")
    @ConfigurationProperties(prefix = "spring.datasource.druid")
    public DataSource dataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    /**
     * 配置事物管理器
     * @return DataSourceTransactionManager
     */
    @Bean(name="transactionManager")
    public DataSourceTransactionManager transactionManager(){
        return new DataSourceTransactionManager(dataSource());
    }

    /**
     * 配置分页插件
     * @return page
     */
    @Bean
    public PaginationInterceptor paginationInterceptor(){
        PaginationInterceptor page = new PaginationInterceptor();
        page.setDialectType("mysql");
        return page;
    }

}

mybatis-plus自带的分页有两种方式:一种是返回list,一种是返回map
在这里插入图片描述
因为我写的是个接口所以我就按照我的代码分享了,知道哪些是核心就行
第一种:返回list
1,StudentService.java定义一个方法

List<Student> selectStudentPage(int current, int size);

2,StudentServiceImpl.java方法实现 (重点)

@Resource
    private StudentMapper studentMapper;
    
    /**
     * 分页1
     * @param current
     * @param size
     * @return   ***   list对象   ***
     */
    @Override
    public List<Student> selectStudentPage(int current, int size) {
        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        //  判断年龄大于20岁的,这里用的是mybatis-plus的条件构造器
        queryWrapper.gt("age",20);
        /**
        *    加上false就不查询总记录数啦,如果不需要的话可以加上false,这样就会少一条sql语句
        *   Page<Student> page = new Page<>(current,size,false);
        */
        Page<Student> page = new Page<>(current,size);
        //   queryWrapper  可以为null  不进行条件判断
        //  返回list 调用  selectPage
        IPage<Student> userIPage = studentMapper.selectPage(page, queryWrapper);
        System.out.println("总页数"+userIPage.getPages());
        System.out.println("总记录数"+userIPage.getTotal());
        //getRecords()分页对象记录列表
        List<Student> records = userIPage.getRecords();
        return records;
    }

StudentController.java接口

	@Autowired
    private StudentService studentService;
/**
     *  分页1   返回list  单表
     * @param current  第几页
     * @param size    每页数量
     * @return   list对象
     */
    @GetMapping("/selectStudentPage/{current}/{size}")
    public Object selectStudentPage(@PathVariable int current,@PathVariable int size){
        List<Student> studentList = studentService.selectStudentPage(current, size);
        return studentList;
    }

在这里插入图片描述
第二种:返回map
1,StudentService.java定义一个方法

List<Map<String, Object>> selectStudentMapPage(int current, int size);

2,StudentServiceImpl.java方法实现 (重点)

    /**
     * 分页2
     * @return   ***  map  ***
     */
    @Override
    public List<Map<String, Object>> selectStudentMapPage(int current, int size) {
        QueryWrapper<Student> wrapper = new QueryWrapper<>();
        wrapper.gt("age",19);
        Page<Student> page = new Page<>(current,size,false);
        //  返回map调用  selectMapsPage
        IPage<Map<String, Object>> mapIPage = studentMapper.selectMapsPage(page, wrapper);
        System.out.println("总页数"+mapIPage.getPages());
        System.out.println("总记录数"+mapIPage.getTotal());
        List<Map<String, Object>> records = mapIPage.getRecords();
        return records;
    }

StudentController.java接口

@GetMapping("/selectStudentMapPage/{current}/{size}")
public Object selectStudentMapPage(@PathVariable int current,@PathVariable int size){
    List<Map<String, Object>> maps = studentService.selectStudentMapPage(current, size);
    return maps;
}

在这里插入图片描述
单表可以不用sql就可以进行分页,如果是多个表关联就需要来写sql语句啦

多表分页
在前面两个实体类的基础下,再添加一个实体类,为了保证实体类的属性和表结构一致,我们就再创建一个传输类,把我们要查的属性写进去。

StudentAndMajorVO .java

// 属性名和要映射的实体类保持一致
@Data
public class StudentAndMajorVO implements Serializable {

    private String id;
    private String name;
    private Integer age;
    private String email;
    private String mname;
}

StudentMapper .xml
as mname 别名要和返回的StudentAndMajorVO中名字一样,不然会找不到,返回null
${ew.customSqlSegment} 是分页的方法

<select id="selectStudentAndMajorXmlPage" resultType="com.mp.entity.vo.StudentAndMajorVO">
    SELECT s.*,m.`name` as mname
    FROM xu_student s
    LEFT JOIN xu_major m
    ON s.m_id = m.id ${ew.customSqlSegment}
</select>

StudentMapper .java 在mapper接口中定义一个方法

package com.mp.dao;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mp.entity.Student;
import com.mp.entity.vo.StudentAndMajorVO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

import java.util.List;

@Mapper
public interface StudentMapper extends BaseMapper<Student>{

	//@Param(Constants.WRAPPER)  固定写法
    IPage<StudentAndMajorVO> selectStudentAndMajorXmlPage(Page<StudentAndMajorVO> page, @Param(Constants.WRAPPER) Wrapper<Student> wrapper);
}

StudentService.java

List<StudentAndMajorVO> selectStudentAndMajorXmlPage(int current, int size);

StudentServiceImpl.java

@Override
public List<StudentAndMajorVO> selectStudentAndMajorXmlPage(int current, int size) {
    QueryWrapper<Student> wrapper = new QueryWrapper<>();
    wrapper.gt("age",19);
    Page<StudentAndMajorVO> page = new Page<>(current,size,false);
    IPage<StudentAndMajorVO> studentAndMajorVOIPage = studentMapper.selectStudentAndMajorXmlPage(page, wrapper);
    List<StudentAndMajorVO> records = studentAndMajorVOIPage.getRecords();
    return records;
}

StudentController.java

@GetMapping("/selectStudentAndMajorXmlPage/{current}/{size}")
public Object selectStudentAndMajorXmlPage(@PathVariable int current,@PathVariable int size){
    List<StudentAndMajorVO> studentAndMajorVOS = studentService.selectStudentAndMajorXmlPage(current, size);
    return studentAndMajorVOS;
}

在这里插入图片描述
在这里插入图片描述

您好!关于您的问题,我可以帮您解答。针对springboot整合mybatis-plus实现多表分页查询实现,可以按照以下步骤进行: 1.在pom.xml文件中添加Mybatis-Plus和Pagehelper的依赖,如下: ``` <!-- Mybatis-Plus依赖 --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.0.5</version> </dependency> <!-- Pagehelper依赖 --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.2.13</version> </dependency> ``` 2.在Mybatis-Plus的配置文件中,指定分页插件。如下: ``` @Configuration @MapperScan("com.example.mapper") public class MybatisPlusConfig { @Bean public PaginationInterceptor paginationInterceptor() { return new PaginationInterceptor(); } } ``` 3.编写Mapper和对应的Mapper.xml文件,进行多表联合查询,并在Mapper接口方法上添加分页参数。如下: ``` //在Mapper接口方法上添加分页参数 public interface UserMapper extends BaseMapper<User> { List<User> selectUserPage(Page<User> page); } <!-- 在Mapper.xml中编写多表联合查询SQL语句 --> <select id="selectUserPage" resultMap="BaseResultMap"> select u.*, r.role_name from user u left join user_role ur on u.id = ur.user_id left join role r on ur.role_id = r.id <where> <if test="username != null and username != ''"> and u.username like concat('%',#{username},'%') </if> </where> </select> ``` 4.在Controller层中,接受分页参数并返回分页结果。如下: ``` @RestController public class UserController { @Autowired private UserMapper userMapper; @GetMapping("/users") public Page<User> selectUserPage(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer size, String username) { Page<User> p = new Page<>(page, size); p = userMapper.selectUserPage(p, username); return p; } } ``` 以上就是整合Mybatis-Plus和Pagehelper实现多表分页查询的具体步骤,希望能对您有所帮助!如果您有其他问题,欢迎继续提问。
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值