• Mybatis-Plus使用Wrapper自定义SQL



    简要说明:Mybatis-Plus使用Wrapper自定义SQL,主要的代码说明,详情可以往后看。
    假设有三张表(这三张表在: SpringBoot整合mybatis-plus-CSDN博客,有 )的关系如图所示
    在这里插入图片描述
    对应的UserMapper.java的主要代码如下

    public interface UserMapper extends BaseMapper<User> {
    
    // 下面的currentPage, pageSize,userId, roleName都是Controller层传入,或者自己看着填写,这里只是说明一下UserMapper.java的参数来源
    		// LambdaQueryWrapper lqw = new LambdaQueryWrapper<>();
    		// 动态SQL,这是真的方便
    		// lqw.like(StringUtils.isNotEmpty(name), User::getName, name);
    		//lqw.eq(age != null && age != 0, User::getAge, age);
    
     /**
             * 假设联表查询,语句是这样的。
             * # 如根据用户姓名、年龄查询用户具有的角色列表。
             * 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.name like '%张%' and su.age = 98;
    
    
            QueryWrapper qw = new QueryWrapper<>();
            // 动态SQL
            qw.like(StringUtils.isNotEmpty(name), "su.name", name);
            qw.eq(age != null && age != 0, "su.age", age);
             */
          
        /**
         * 单表查询,Mybatis-Plus使用Wrapper自定义SQL
         * 这个是为了下面联表查询铺垫,这个主要是了解,
         * Mybatis-Plus使用Wrapper自定义SQL如何使用
         */
        @Select("select * from sys_user ${ew.customSqlSegment}")
        // 这里需要注意了@Param("ew")这里面只能是ew
        List<User> getAllWrapperSql(@Param("ew") LambdaQueryWrapper<User> wrapper);
        // 使用下面这个方法也行,使用Mp内置的枚举类,Constants.WRAPPER 这个就是 ew
        // List getAllWrapperSql(@Param(Constants.WRAPPER) LambdaQueryWrapper wrapper);
    
        /**
         * 联表查询,Mybatis-Plus使用Wrapper自定义SQL,在xml中使用
         * 根据用户姓名、年龄获取对应用户具有的角色列表
         */
        // 注意这里,只能是ew
        List<RoleVo> getRoleListByUserNameMulTable(@Param(Constants.WRAPPER) QueryWrapper qw);
        // 像下面这样写也可以
        // List getRoleListByUserNameMulTable(@Param("ew") LambdaQueryWrapper lqw);
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45

    对应的UserMapper.xml如下所示

    
    DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.ygy.mapper.UserMapper">
        
        <select id="getRoleListByUserNameMulTable" resultType="com.ygy.domain.vo.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 ${ew.customSqlSegment}
        select>
    mapper>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    大概结果如下所示:
    联表查询,Mybatis-Plus使用Wrapper自定义SQL,结果如下所示:
    在这里插入图片描述

    IDEA控制台中打印的SQL语句

    在这里插入图片描述

    下面有详细的说明,感兴趣的可以往下看。下面有详细的说明,感兴趣的可以往下看。下面有详细的说明,感兴趣的可以往下看。

    准备工作

    SpringBoot2.7.10 + JDK17 + MySQL8…30社区版 + Mybatis-Plus3.5.3,SpringBoot整合Mybatis-Plus看这篇文章:SpringBoot整合mybatis-plus-CSDN博客 这里有说明SpringBoot + Mybatis-Plus的整合和下文需要用到的数据库表数据,这里需要用到这篇文章中的三张表,实现联表查询,以及对应的Maven依赖,都有说明。直接从这篇文章中导入即可。

    Mybatis-Plus使用Wrapper自定义SQL

    注意事项

    具体看官网,条件构造器 | MyBatis-Plus (baomidou.com)

    需要mybatis-plus版本 >= 3.0.7 param 参数名要么叫ew,要么加上注解@Param(Constants.WRAPPER) 使用${ew.customSqlSegment} 不支持 Wrapper 内的entity生成where语句

    对于单表查询操作,Mybatis-Plus的Wrapper条件构造器,很方便。特别是LambdaQueryWrapper,我用着感觉很好用,这个动态SQL条件构造还是很好用的。但是在联表查询的时候,如果还想用LambdaQueryWrapper这条件构造器,就需要使用Mybatis-Plus使用Wrapper自定义SQL了。

    目录结构如下所示

    在这里插入图片描述

    可以直接复制下面的代码,或者参考SpringBoot整合mybatis-plus-CSDN博客,中代码生成器生成对应的文件,然后在对应的文件中写代码方法。

    domain层

    User.java

    package com.ygy.domain;
    
    import com.baomidou.mybatisplus.annotation.IdType;
    import com.baomidou.mybatisplus.annotation.TableId;
    import com.baomidou.mybatisplus.annotation.TableName;
    import java.io.Serializable;
    import io.swagger.annotations.ApiModel;
    import io.swagger.annotations.ApiModelProperty;
    import lombok.Getter;
    import lombok.Setter;
    
    /**
     * 

    * 用户表 *

    * * @author ygy * @since 2023-11-05 */
    @Getter @Setter @TableName("sys_user") @ApiModel(value = "User对象", description = "用户表") public class User implements Serializable { private static final long serialVersionUID = 1L; @ApiModelProperty("用户ID") @TableId(value = "id", type = IdType.AUTO) private Long id; @ApiModelProperty("姓名") private String name; @ApiModelProperty("年龄") private Integer age; @ApiModelProperty("性别(0,女,1,男)") private Integer sex; }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41

    RoleVo.java

    package com.ygy.domain.vo;
    
    import io.swagger.annotations.ApiModel;
    import io.swagger.annotations.ApiModelProperty;
    import lombok.Data;
    
    @Data
    @ApiModel(value = "RoleVo对象", description = "角色表")
    public class RoleVo {
    
        @ApiModelProperty("角色名称")
        private String RoleName;
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    Controller层

    UserController.java

    package com.ygy.controller;
    
    import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
    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.ygy.domain.User;
    import com.ygy.domain.vo.PageVo;
    import com.ygy.domain.vo.RoleVo;
    import com.ygy.service.IUserService;
    import io.swagger.annotations.Api;
    import io.swagger.annotations.ApiOperation;
    import io.swagger.annotations.ApiParam;
    import org.apache.commons.lang3.StringUtils;
    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.RestController;
    
    import java.util.List;
    
    /**
     * 

    * 用户表 前端控制器 *

    *其中 @ApiParam("当前页码数")、@ApiParam("每页显示条数")、@ApiOperation("分页获取用户列表")是swagger的注解 * @author ygy * @since 2023-11-05 */
    @Api(tags = "用户管理模块") // 这个是swagger的注解 @RestController @RequestMapping("/user") public class UserController { @Autowired private IUserService userService; @GetMapping @ApiOperation("单表查询条件构造器") public List<User> getAll(@ApiParam("姓名") String name, @ApiParam("年龄") Integer age) { // 从这里可以看出,单表查询结合LambdaQueryWrapper这条件构造器还是挺好用的 // 什么都不用写,直接调用MP内置的方法,简单方便 LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>(); // 动态SQL,这是真的方便 lqw.like(StringUtils.isNotEmpty(name), User::getName, name); lqw.eq(age != null && age != 0, User::getAge, age); List<User> userList = userService.list(lqw); return userList; } /** * 单表查询,Mybatis-Plus使用Wrapper自定义SQL * 这个是为了下面联表查询铺垫,这个主要是了解, * Mybatis-Plus使用Wrapper自定义SQL如何使用 */ @GetMapping("/getAllWrapperSql") @ApiOperation("单表查询,Mybatis-Plus使用Wrapper自定义SQL") public List<User> getAllWrapperSql(@ApiParam("姓名") String name, @ApiParam("年龄") Integer age) { LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>(); lqw.like(StringUtils.isNotEmpty(name), User::getName, name); lqw.eq(age != null && age != 0, User::getAge, age); List<User> userList = userService.getAllWrapperSql(lqw); return userList; } /** * 联表查询不用,Mybatis-Plus的条件构造器时 * 根据用户姓名、年龄获取对应用户具有的角色列表 */ @GetMapping("/getRoleListByUserName") @ApiOperation("联表查询,不用Mybatis-Plus的条件构造器时") public List<RoleVo> getRoleListByUserName(@ApiParam("姓名") String name, @ApiParam("年龄") Integer age) { List<RoleVo> roleVoList = userService.getRoleListByUserName(name, age); return roleVoList; } /** * 联表查询,Mybatis-Plus使用Wrapper自定义SQL * 根据用户姓名、年龄获取对应用户具有的角色列表 */ @GetMapping("/getRoleListByUserNameMulTable") @ApiOperation("联表查询,Mybatis-Plus使用Wrapper自定义SQL") public List<RoleVo> getRoleListByUserNameMulTable(@ApiParam("姓名") String name, @ApiParam("年龄") Integer age) { /** * 假设联表查询,语句是这样的。 * # 如根据用户姓名、年龄查询用户具有的角色列表。 * 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.name like '%张%' and su.age = 98; */ QueryWrapper qw = new QueryWrapper<>(); // 动态SQL qw.like(StringUtils.isNotEmpty(name), "su.name", name); qw.eq(age != null && age != 0, "su.age", age); List<RoleVo> roleVoList = userService.getRoleListByUserNameMulTable(qw); return roleVoList; } }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102

    Service层

    IUserService.java

    package com.ygy.service;
    
    import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
    import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
    import com.baomidou.mybatisplus.core.metadata.IPage;
    import com.ygy.domain.User;
    import com.baomidou.mybatisplus.extension.service.IService;
    import com.ygy.domain.vo.RoleVo;
    
    import java.util.List;
    
    /**
     * 

    * 用户表 服务类 *

    * * @author ygy * @since 2023-11-05 */
    public interface IUserService extends IService<User> { /** * 单表查询,Mybatis-Plus使用Wrapper自定义SQL * 这个是为了下面联表查询铺垫,这个主要是了解, * Mybatis-Plus使用Wrapper自定义SQL如何使用 */ List<User> getAllWrapperSql(LambdaQueryWrapper<User> lqw); /** * 联表查询不用,Mybatis-Plus的条件构造器时 * 根据用户姓名、年龄获取对应用户具有的角色列表 */ List<RoleVo> getRoleListByUserName(String name, Integer age); /** * 联表查询,Mybatis-Plus使用Wrapper自定义SQL * 根据用户姓名、年龄获取对应用户具有的角色列表 */ List<RoleVo> getRoleListByUserNameMulTable(QueryWrapper qw); }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41

    ServiceImpl

    UserServiceImpl.java

    package com.ygy.service.impl;
    
    import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
    import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
    import com.baomidou.mybatisplus.core.metadata.IPage;
    import com.ygy.domain.User;
    import com.ygy.domain.vo.RoleVo;
    import com.ygy.mapper.UserMapper;
    import com.ygy.service.IUserService;
    import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import java.util.List;
    
    /**
     * 

    * 用户表 服务实现类 *

    * * @author ygy * @since 2023-11-05 */
    @Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService { @Autowired private UserMapper userMapper; /** * 单表查询,Mybatis-Plus使用Wrapper自定义SQL * 这个是为了下面联表查询铺垫,这个主要是了解, * Mybatis-Plus使用Wrapper自定义SQL如何使用 */ @Override public List<User> getAllWrapperSql(LambdaQueryWrapper<User> lqw) { List<User> userList = userMapper.getAllWrapperSql(lqw); return userList; } /** * 联表查询不用,Mybatis-Plus的条件构造器时 * 根据用户姓名、年龄获取对应用户具有的角色列表 */ @Override public List<RoleVo> getRoleListByUserName(String name, Integer age) { List<RoleVo> roleVoList = userMapper.getRoleListByUserName(name, age); return roleVoList; } /** * 联表查询,Mybatis-Plus使用Wrapper自定义SQL * 根据用户姓名、年龄获取对应用户具有的角色列表 */ @Override public List<RoleVo> getRoleListByUserNameMulTable(QueryWrapper qw) { List<RoleVo> roleVoList = userMapper.getRoleListByUserNameMulTable(qw); return roleVoList; } }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61

    Mapper层

    UserMapper.java

    package com.ygy.mapper;
    
    import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
    import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
    import com.baomidou.mybatisplus.core.metadata.IPage;
    import com.baomidou.mybatisplus.core.toolkit.Constants;
    import com.ygy.domain.User;
    import com.baomidou.mybatisplus.core.mapper.BaseMapper;
    import com.ygy.domain.vo.RoleVo;
    import org.apache.ibatis.annotations.Param;
    import org.apache.ibatis.annotations.Select;
    
    import java.util.List;
    
    /**
     * 

    * 用户表 Mapper 接口 *

    * * @author ygy * @since 2023-11-05 */
    public interface UserMapper extends BaseMapper<User> { /** * 单表查询,Mybatis-Plus使用Wrapper自定义SQL * 这个是为了下面联表查询铺垫,这个主要是了解, * Mybatis-Plus使用Wrapper自定义SQL如何使用 */ @Select("select * from sys_user ${ew.customSqlSegment}") // 这里需要注意了@Param("ew")这里面只能是ew List<User> getAllWrapperSql(@Param("ew") LambdaQueryWrapper<User> wrapper); // 使用下面这个方法也行,使用Mp内置的枚举类,Constants.WRAPPER 这个就是 ew // List getAllWrapperSql(@Param(Constants.WRAPPER) LambdaQueryWrapper wrapper); /** * 联表查询不用,Mybatis-Plus的条件构造器时,在xml中使用 * 根据用户姓名、年龄获取对应用户具有的角色列表 */ List<RoleVo> getRoleListByUserName(String name, Integer age); /** * 联表查询,Mybatis-Plus使用Wrapper自定义SQL,在xml中使用 * 根据用户姓名、年龄获取对应用户具有的角色列表 */ // 注意这里,只能是ew List<RoleVo> getRoleListByUserNameMulTable(@Param(Constants.WRAPPER) QueryWrapper qw); // 像下面这样写也可以 // List getRoleListByUserNameMulTable(@Param("ew") LambdaQueryWrapper lqw); }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51

    UserMapper.xml

    
    DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.ygy.mapper.UserMapper">
    
        
        <select id="getRoleListByUserName" resultType="com.ygy.domain.vo.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>
                <if test="name != null and name != ''">
                    AND su.name like concat('%', #{name}, '%')
                if>
                <if test="age != null and age != ''">
                    AND su.age = #{age}
                if>
            where>
        select>
    
        
        <select id="getRoleListByUserNameMulTable" resultType="com.ygy.domain.vo.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 ${ew.customSqlSegment}
        select>
    
    
    mapper>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37

    结果如下所示:

    单表查询条件构造器

    单表查询条件构造器,结果如下所示:

    在这里插入图片描述

    IDEA控制台中打印的SQL语句为

    在这里插入图片描述

    单表查询,Mybatis-Plus使用Wrapper自定义SQL

    单表查询,Mybatis-Plus使用Wrapper自定义SQL的结果如下所示

    在这里插入图片描述

    IDEA控制台中打印的SQL语句为

    在这里插入图片描述

    联表查询不用,Mybatis-Plus的条件构造器时

    联表查询不用,Mybatis-Plus的条件构造器时结果如下所示

    在这里插入图片描述

    IDEA控制台中打印的SQL语句为

    在这里插入图片描述

    联表查询,Mybatis-Plus使用Wrapper自定义SQL

    联表查询,Mybatis-Plus使用Wrapper自定义SQL,结果如下所示:
    在这里插入图片描述

    IDEA控制台中打印的SQL语句为

    在这里插入图片描述

    总结

    这么一看,还不如像(联表查询不用,Mybatis-Plus的条件构造器)时这里的方法呢,可读性也不是很好。不过也有它的用处,它的动态SQL强啊,类似与select * from sys_user where id in(1,2,3); 语句,当然不是单表(联表使用或者复杂的SQL查询语句,这个或许会方便一些),如果使用Mybatis的写法,在xml需要使用foreach标签等,但是使用这个Mp的自定义SQL,可以直接传入选择in方法,然后根据对应的要求传入参数即可。

  • 相关阅读:
    分类神经网络1:VGGNet模型复现
    三万字带你了解那些年面过的Java八股文
    MySQL库的操作
    docker run -v 用户目录的权限配置
    MYSQL-->InnoDB引擎底层原理
    51单片机-第三节-LCD1602调试工具,矩阵键盘
    干货|建模3D Max中常见问题
    pyside6开发-01-开发环境搭建
    vue3笔记
    Java手写基数排序和算法案例拓展
  • 原文地址:https://blog.csdn.net/m0_62317155/article/details/134276903