开发者

使用MyBatis-Plus实现联表查询分页的示例代码

开发者 https://www.devze.com 2024-10-17 12:12 出处:网络 作者: 李少兄
目录前言环境准备项目环境添加依赖配置数据库连接实体类定义分页返回对象请求参数封装DAO 层接口定义映射文件Service 层接口定义实现类Controller 层测试前言
目录
  • 前言
  • 环境准备
    • 项目环境
    • 添加依赖
    • 配置数据库连接
  • 实体类定义
    • 分页返回对象
      • 请求参数封装
        • DAO 层
          • 接口定义
          • 映射文件
        • Service 层
          • 接口定义
          • 实现类
        • Controller 层
          • 测试

            前言

            在本文中,我们将详细介绍如何使用 MyBATis-Plus 的分页插件在 XML 文件中实现联表查询的分页功能。

            环境准备

            项目环境

            • Java 版本: 1.8+
            • Spring Boot 版本: 2.x
            • MyBatis-Plus 版本: 3.x
            • 数据库: mysql

            添加依赖

            确保你的项目中添加了 MyBatis-Plus 的相关依赖。如果你使用 Maven,可以在 pom.xml 文件中添加如下依赖:

            <dependencies>
                <dependency>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-data-mybatis-plus</artifactId>
                </dependency>
                <dependency>
                   js <groupId>mysql</groupId>
                    <artifactId>mysql-connector-java</artifactId>
                    <scope>runtime</scope>
                </dependency>
                <!-- 其他依赖 -->
            </dependencies>
            

            配置数据库连接

            在 application.properties 或 application.yml 文件中配置数据库连接信息:

            spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
            spring.datasource.username=root
            spring.datasource.password=root
            spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
            

            实体类定义

            首先,定义几个基本的实体类:

            User.java

            package com.microsun.integrated.framework.domain;
            
            import lombok.AllArgsConstructor;
            import lombok.Data;
            import lombok.NoArgsConstructor;
            
            @Data
            @NoArgsConstructor
            @AllArgsConstructor
            public class User {
                private Long id;
                private String name;
                // Getters and Setters
            }
            

            UserRole.java

            package com.microsun.integrated.framework.domain;
            
            import lombok.AllArgsConstructor;
            import lombok.Data;
            import lombok.NoArgsConstructor;
            
            @Data
            @NoArgsConstructor
            @AllArgsConstructor
            public class UserRole {
                private Long userId;
                private Long roleId;
                // Getters and Setters
            }
            

            Role.java

            package com.microsun.integrated.framework.domain;
            
            import lombok.AllArgsConstructor;
            import lombok.Data;
            import lombok.NoArgsConstructor;
            
            @Data
            @NoArgsConstructor
            @AllArgsConstructor
            public class Role {
                private Long id;
                private String roleName;
                // Getters and Setters
            }
            

            RoleVo.java (用于展示的视图对象)

            package com.microsun.integrated.framework.domain;
            
            import lombok.AllArgsConstructor;
            import lombok.Data;
            import lombok.NoArgsConstructor;
            
            @Data
            @NoArgsConstructor
            @AllArgsConstructor
            public class RoleVo {
                private Long userId;
                private String roleName;
                // Getters and Setters
            }
            

            分页返回对象

            为了封装分页返回的对象,我们定义了一个 PageVO 类:

            PageVO.java

            package com.microsun.integrated.framework.domain;
            
            import io.swagger.v3.oas.annotations.media.Schema;
            import lombok.AllArgsConstructor;
            import lombok.Data;
            import lombok.NoArgsConstructor;
            
            import java.util.List;
            
            @Data
            @NoArgsConstructor
            @AllArgsConstructor
            @Schema(title = "分页")
            public class PageVO<T> {
            
                @Schema(title = "总数")
                private Long total;
            
                @Schema(title = "每页显示条数")
                private Long size;
            
                @Schema(title = "当前页")
                private Long current;
            
                @Schema(title = "数据列表")
                private List<T> records;
            }
            

            请求参数封装

            接下来,我们创建一个 BO (Business Object) 对象来封装请求参数:

            UserRoleQueryBO.java

            package com.microsun.integrated.framework.domain;
            
            import io.swagger.v3.oas.annotations.media.Schema;
            import lombok.AllArgsConstructor;
            import lombok.Data;
            import lombok.NoArgsConstructor;
            
            /**
             * 用户角色查询 BO
             */
            @Data
            @NoArgsConstructor
            @AllArgsConstructor
            @Schema(title = "用户角色查询 BO")
            public class UserRoleQueryBO {
                /**
                 * 用户ID
                 */
                @Schema(title = "用户ID")
                private Long userId;
            
                /**
                 * 角色名称
                 */
                @Schema(title = "角色名称")
                private String roleName;
            }
            

            DAO 层

            接口定义

            在 DAO 层创建接口并定义分页查询方法:

            UserMapper.java

            package com.microsun.integrated.framework.mapper;
            
            import com.baomidou.mybatisplus.core.metadata.IPage;
            import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
            import com.microsun.integrated.framework.domain.RoleVo;
            import com.microsun.integrated.framework.domain.UserRoleQueryBO;
            import org.apache.ibatis.annotations.Param;
            
            public interface UserMapper {
                /**
                 * 联表查询实现分页,根据用户ID查询用户具有的角色列表
                 * 把联表查询得到的数据当成一张单表来看
                 *
                 * @param page 分页对象
                 * @param bo   查询条件对象
                 * @return 分页后的角色列表
                 */
                IPage<RoleVo> getUlserListByMulTable(@Param("page") IPage<RoleVo> page, @Param("bo") UserRoleQueryBO bo);
            }
            

            映射文件

            创建对应的 XML 映射文件 UserMapper.xml,并在其中编写 SQL 查询语句:

            UserMapper.xml

            <?xml version="1.0" encoding="UTF-8" ?>
            <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
            <mapper namespace="com.microsun.integrated.framework.mapper.UserMapper">
                <select id="getUlserListByMulTable" resultType="com.microsun.integrated.framework.domain.RoleVo">
                    select sr.role_name
                    from sys_user su
                    left join sys_user_role sur on su.id = sur.user_id
                    left join sys_role sr on sur.role_id = sr.id
                    where su.id = #{bo.userId}
                    <if test="bo.roleName != null and bo.roleName != ''">
                        and sr.role_name like concat('%', #{bo.roleName}, '%')
                    </if>
                    <include refid="mp_limit_sql"/>
                </select>
            </mapper>
            

            这里使用 <if> 标签来动态拼接 SQL 语句,并使用 <include refid="mp_limit_sql"/> 来引用 MyBatis-Plus 提供的分页 SQL 语法。

            Servic编程客栈e 层

            接口定义

            定义 Service 接口:

            UserService.java

            package com.microsun.integrated.framework.service;
            
            import com.microsun.integrated.framework.domain.PageVO;
            import com.microsun.integrated.framework.domain.RoleVo;
            import com.microsun.integrated.framework.domain.UserRoleQueryBO;
            
            public interface UserService {
                /**
                 * 获取用户角色列表
                 *
                 * @param currentPage 当前页码
                 * @param pageSize    每页数量
                 * @param bo          查询条件对象
                 * @return 分页后的角色列表
                 */
                PageVO<RoleVo> getUserRoleList(int currentPage, int pageSize, UserRoleQueryBO bo);
            }
            

            实现类

            实现 pythonService 接口:

            UserServiceImpl.java

            package com.microsun.integrated.framework.service.impl;
            
            import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
            import com.microsun.integrated.framework.domain.PageVO;
            import com.microsun.integrated.framework.domain.RoleVo;
            import com.microsun.integrated.framework.domain.UserRoleQueryBO;
            import com.microsun.integrated.framework.mapper.UserMapper;
            import com.microsun.integrated.framework.service.UserService;
            import org.springframework.beans.factory.annotation.Autowired;
            import org.springframework.stereotype.Service;
            import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
            
            import java.util.List;
            
            @Service
            public class UserServiceImpl extends ServiceImpl<UserMapper, RoleVo> implements UserService {
            
                @Autowired
                private UserMapper userMapper;
            
                @Override
                public PageVO<RoleVo> getUserRoleList(int currentPage, int pageSize, UserRoleQueryBO bo) {
                    IPage<RoleVo> page = new Page<>(currentPage, pageSize);
                    IPage<RoleVo> result = userMapper.getUlserListByMulTable(page, bo);
            
                    PageVO<RoleVo> pageVO = new PageVO<>();
                    pageVO.setTotal(result.getTotal());
                    pageVO.setSize(result.getSize());
                    pageVO.setCurrent(result.getCurrent());
                    pageVO.setRecords(result.getRecords());
            
                    return pageVO;
                }
            }
            

            Controller 层

            创建 Controller 类来处理前端请求:

            UserController.java

            package com.microsun.integrated.framework.controller;
            
            import com.microsun.integrated.framework.domain.PageVO;
            import com.microsun.integrated.framework.domain.RoleVo;
            import com.microsun.integrated.framework.domain.UserRoleQueryBO;
            import com.microsun.integrated.framework.service.UserService;
            import org.springframework.beans.factory.annotation.Autowired;
            import org.springframework.web.bind.annotation.GetMapping;
            import org.springframework.web.bind.annotation.RequestMapping;
            import org.springframework.web.bind.annotation.RequestParam;
            import org.springframework.web.bind.annotation.RestController;
            
            import javax.servlet.http.HttpServletRequest;
            
            @RestController
            @RequestMapping("/users")
            public class UserController {
            
                @Autowired
                private UserService userService;
            
                @GetMapping("/roles")
                public PageVO<RoleVo> getUserRoleList(
                        @RequestParam(value = "currentPage", defaultValue = "1") int currentPage,
                        @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
                        @RequestParam(value = "userId", required = false) Long userId,
                        @RequestParam(value = "roleName", required = false) String roleName) {
            
                    UserRoleQueryBO bo = new UserRoleQueryBO(userId, roleName);
                    return userService.getUserRoleList(currentPage, pageSize, bo);
                }
            }
            

            测试

            现在你可以启动 Spring Boot 应用并测试你的分页联表查询功能。可以通过发送 HTTP GET 请求到 /users/roles 来测试上述功能,例如:

            • GET /users/roles?currentPage=1&pageSize=2&userId=1&roleName=admin
            • GET /users/roles?currentPage=1&pageSize=2&userId=1

            通过这个示例编程,你学会了如何封装请求参数,并在 MyBatis-Plus 的 XML 文件中使用这些封装好的参数。这有助于保持wRRVEB代码的整洁性和可维护性。

            到此这篇关于使用MyBatis-Plus实现联表查询分页的示例代码的文章就介绍到这了,更多相关MyBatis-Plus 联表查询分页内容请搜索编程客栈(www.devze.com)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程客栈(www.devze.com)!

            0

            精彩评论

            暂无评论...
            验证码 换一张
            取 消

            关注公众号