Java--MybatisPlus Wrapper构造器;分页;MP代码生成器(四)

阅读前可先参考

https://blog.csdn.net/MinggeQingchun/article/details/126521908

https://blog.csdn.net/MinggeQingchun/article/details/126533536

https://blog.csdn.net/MinggeQingchun/article/details/126539292

一、Wrapper构造器

条件构造器 | MyBatis-Plus

条件构造器 Wrapper 就是用来封装CRUD方法参数条件的一个接口,其底层有很多的子类,最主要的就是最下面的四个子类:

QueryWrapper:用来删改查

UpdateWrapper:在修改操作时不必创建实体类对象的操作

LambdaQueryWrapper LambdaUpdateWrapper 则是在字段参数的调用上进行了升级,其他都一样。因为增删改查中的增加记录不需要条件即可完成,所以增加方法无需条件构造器wrapper,其他的删改查则是有这个条件构造器参数的

AbstractWrapper: 

QueryWrapper(LambdaQueryWrapper) 和 UpdateWrapper(LambdaUpdateWrapper) 的父类
用于生成 sql 的 where 条件, entity 属性也用于生成 sql 的 where 条件

函数名(条件)说明
allEq基于map的相等
eq等于=
ne不等于>
gt大于>
ge大于等于>=
lt小于<
le小于等于<=
betweenBETWEEN 值1AND值⒉
notBetweenNOT BETWEEN 值1AND值2
likeLIKE '%值%'
notlikeNOT LIKE'%值%'
likeLeftLIKE '%值'
likeRightLIKE '值%'
isNull字段IS NULL
isNotNull字段IS NOT NULL
in字段IN(value1, value2,...)
notIn字段NOT IN(value1, value2,...)
inSql

字段IN ( sql语句)

例: inSql""age", "1,2,3")--->age in (1,2,3,4,5,6)

例: insql(" id" , "select id from table where id <3")--sidin (select id from table where id <3)

notInSql字段NOT IN ( sql语句)
groupByGROUP BY字段
orderByAsc升序ORDER BY字段,...ASC
orderByDesc降序ORDER BY字段,... DESC
orderBy

自定义字段排序

having条件分组
orOR语句,拼接+OR字段=值
andAND语句,拼接+AND字段=值
apply拼接sql
last在sql语句后拼接自定义条件
exists拼接EXISTS ( sql语句)
notExists拼接NOT EXISTS ( sql语句)
nested正常嵌套不带AND或者OR

1、allEq;基于map的相等

@Test
    public void testAllEq() {
        QueryWrapper<Student> qw = new QueryWrapper<>();
        //组装条件
        Map<String, Object> param = new HashMap<>();
        //map<key,value> key列名 , value:查询的值
        param.put("name", "张三");
        param.put("age", 22);
        param.put("status", null);

        qw.allEq(param);
        //调用MP自己的查询方法
        //SELECT id,name,age,email,status FROM student WHERE name = ? AND age = ?
        List<Student> students = studentMapper.selectList(qw);
        students.forEach(stu -> System.out.println(stu));
    }

    /**
     * 1、Map对象中有 key的value是null
     * 使用的是 qw.allEq(param,true);
     * 结果:WHERE name = ? AND age IS NULL
     * 
     * 2、Map对象中有 key的value是null
     * qw.allEq(param,false);
     * 结果:WHERE name = ?
     * 
     * 总结:
     * allEq(map,boolean)
     * true:处理null值,where 条件加入 字段 is null
     * false:忽略null ,不作为where 条件
     */
    @Test
    public void testAllEq1() {
        QueryWrapper<Student> qw = new QueryWrapper<>();
        //组装条件
        Map<String, Object> param = new HashMap<>();
        //map<key,value> key列名 , value:查询的值
        param.put("name", "张三");
        param.put("age", 22);
        param.put("status", null);

        qw.allEq(param,false);
        //调用MP自己的查询方法
        //SELECT id,name,age,email,status FROM student WHERE name = ? AND age = ?
        List<Student> students = studentMapper.selectList(qw);
        students.forEach(stu -> System.out.println(stu));
    }

2、eq;等于=

/**
     * eq 等于=
     * eq("列名",值)
     */
    @Test
    public void testEq() {
        QueryWrapper<Student> qw = new QueryWrapper<>();
        //组成条件
        qw.eq("name", "李四");
        //WHERE name = ?
        List<Student> students = studentMapper.selectList(qw);
        students.forEach(stu -> System.out.println("查询eq:" + stu));

    }

3、ne;不等于 <>

/**
     * ne 不等于 <>
     * ne("列名",值)
     */
    @Test
    public void testNe() {
        QueryWrapper<Student> qw = new QueryWrapper<>();
        //组成条件
        qw.ne("name", "张三");
        // WHERE name <> ?
        List<Student> students = studentMapper.selectList(qw);
        students.forEach(stu -> System.out.println("查询ne:" + stu));
    }

4、gt;大于 >

/**
     * gt 大于( > )
     */
    @Test
    public void testGt() {
        QueryWrapper<Student> qw = new QueryWrapper<>();
        qw.gt("age", 30); //age > 30
        // WHERE age > ?
        List<Student> students = studentMapper.selectList(qw);
        students.forEach(stu -> System.out.println("stu:" + stu));
    }

5、ge;大于等于 >=

/**
     * ge 大于等于 ( >=)
     */
    @Test
    public void testGe() {
        QueryWrapper<Student> qw = new QueryWrapper<>();
        qw.ge("age", 31);// >=31
        //WHERE age >= ?
        List<Student> students = studentMapper.selectList(qw);
        students.forEach(stu -> System.out.println("student:" + stu));
    }

6、lt;小于

/**
     * lt 小于 <
     */
    @Test
    public void testLt() {
        QueryWrapper<Student> qw = new QueryWrapper<>();
        qw.lt("age", 32);
        // WHERE age < ?
        List<Student> students = studentMapper.selectList(qw);
        students.forEach(stu -> System.out.println("student:" + stu));
    }

7、le 小于等于 <=

/**
     * le 小于等于 <=
     */
    @Test
    public void testLe() {
        QueryWrapper<Student> qw = new QueryWrapper<>();
        qw.le("age", 32);
        //  WHERE age <= ?
        List<Student> students = studentMapper.selectList(qw);
        students.forEach(stu -> System.out.println("student:" + stu));
    }

8、between ( ? and ? )

/**
     * between ( ? and ? )
     */
    @Test
    public void testBetween() {
        QueryWrapper<Student> qw = new QueryWrapper<>();
        //between("列名",开始值,结束值)
        qw.between("age", 22, 28);
        // where age >= 12 and age < 28
        List<Student> students = studentMapper.selectList(qw);
        students.forEach(stu -> System.out.println(stu));
    }

9、notBetween(不在范围区间内)

/**
     * notBetween(不在范围区间内)
     */
    @Test
    public void testNotBetween() {
        QueryWrapper<Student> qw = new QueryWrapper<>();
        qw.notBetween("age", 18, 28);
        //WHERE age NOT BETWEEN ? AND ?
        // where age < 18 or age > 28
        List<Student> students = studentMapper.selectList(qw);
        students.forEach(stu -> System.out.println(stu));
    }

10、like 匹配某个值

/**
     * like 匹配某个值
     */
    @Test
    public void testLike() {
        QueryWrapper<Student> qw = new QueryWrapper<>();
        qw.like("name", "张");
        // WHERE name LIKE %张%
        List<Student> students = studentMapper.selectList(qw);
        students.forEach(stu -> System.out.println(stu));
    }

11、notLike 不匹配某个值

/**
     * notLike 不匹配某个值
     */
    @Test
    public void testNotLike() {
        QueryWrapper<Student> qw = new QueryWrapper<>();
        qw.notLike("name", "张");
        //  WHERE name NOT LIKE ?  %张%
        List<Student> students = studentMapper.selectList(qw);
        students.forEach(stu -> System.out.println(stu));
    }

12、likeLeft "%值"

/**
     * likeLeft "%值"
     */
    @Test
    public void testLikeLeft() {
        QueryWrapper<Student> qw = new QueryWrapper<>();
        qw.likeLeft("name", "张");
        //WHERE name LIKE %张
        List<Student> students = studentMapper.selectList(qw);
        students.forEach(student -> System.out.println(student));
    }

13、likeRight "%值"

/**
     * likeRight "%值"
     */
    @Test
    public void testLikeRight() {
        QueryWrapper<Student> qw = new QueryWrapper<>();
        qw.likeRight("name", "李");
        //WHERE name LIKE 李%
        List<Student> students = studentMapper.selectList(qw);
        students.forEach(student -> System.out.println(student));
    }

14、isNull , 判断字段是 null

/**
     * isNull , 判断字段是 null
     */
    @Test
    public void testIsNull(){
        QueryWrapper<Student> qw = new QueryWrapper<>();
        //判断email is null
        //WHERE email IS NULL
        qw.isNull("email");
        List<Student> students = studentMapper.selectList(qw);
        students.forEach(student -> System.out.println(student));
    }

15、isNotNull , 判断字段是 is not null

/**
     * isNotNull , 判断字段是 is not null
     */
    @Test
    public void testIsNotNull(){
        QueryWrapper<Student> qw = new QueryWrapper<>();
        // WHERE email IS NOT NULL
        qw.isNotNull("email");
        List<Student> students = studentMapper.selectList(qw);
        students.forEach(student -> System.out.println(student));
    }

16、in 值列表

/**
     * in 值列表
     */
    @Test
    public void testIn(){
        QueryWrapper<Student> qw = new QueryWrapper<>();
        //in(列名,多个值的列表)
        //WHERE name IN (?,?,?)
        qw.in("name","张三","李四","周丽");
        List<Student> students = studentMapper.selectList(qw);
        students.forEach(student -> System.out.println(student));
    }


/**
     * in 值列表
     */
    @Test
    public void testIn2(){
        QueryWrapper<Student> qw = new QueryWrapper<>();
        List<Object> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        //WHERE status IN (?,?)
        qw.in("status",list);
        List<Student> students = studentMapper.selectList(qw);
        students.forEach(student -> System.out.println(student));
    }

17、notIn 不在值列表

/**
     * notIn 不在值列表
     */
    @Test
    public void testNoIn(){
        QueryWrapper<Student> qw = new QueryWrapper<>();
        //in(列名,多个值的列表)
        //WHERE name NOT IN (?,?,?)
        qw.notIn("name","张三","李四","周丽");
        List<Student> students = studentMapper.selectList(qw);
        students.forEach(student -> System.out.println(student));
    }

18、inSql() : 使用子查询

/**
     * inSql() : 使用子查询
     */
    @Test
    public void testInSQL(){
        QueryWrapper<Student> qw = new QueryWrapper<>();
        //WHERE age IN (select age from student where id=1)
        qw.inSql("age","select age from student where id=1");
        List<Student> students = studentMapper.selectList(qw);
        students.forEach(student -> System.out.println(student));
    }

19、notInSql() : 使用子查询

/**
     * notInSql() : 使用子查询
     */
    @Test
    public void testNotInSQL(){
        QueryWrapper<Student> qw = new QueryWrapper<>();
        //WHERE age NOT IN (select age from student where id=1)
        qw.notInSql("age","select age from student where id=1");
        List<Student> students = studentMapper.selectList(qw);
        students.forEach(student -> System.out.println(student));
    }

20、groupBy:分组

/**
     * groupBy:分组
     */
    @Test
    public void testGroupby(){
        QueryWrapper<Student> qw = new QueryWrapper<>();
        qw.select("name,count(*) personNumbers");//select name,count(*) personNumbers
        qw.groupBy("name");
        // SELECT name,count(*) personNumbers FROM student GROUP BY name
        List<Student> students = studentMapper.selectList(qw);
        students.forEach(student -> System.out.println(student));
    }

21、orderbyAsc : 按字段升序

/**
     * orderbyAsc : 按字段升序
     */
    @Test
    public void testOrderByAsc(){
        QueryWrapper<Student> qw= new QueryWrapper<>();
        //FROM student ORDER BY name ASC , age ASC
        qw.orderByAsc("name","age");
        List<Student> students = studentMapper.selectList(qw);
        students.forEach(student -> System.out.println(student));
    }

22、orderbyDesc : 按字段降序

/**
     * orderbyDesc : 按字段降序
     */
    @Test
    public void testOrderByDesc(){
        QueryWrapper<Student> qw= new QueryWrapper<>();
        // ORDER BY name DESC , id DESC
        qw.orderByDesc("name","id");
        List<Student> students = studentMapper.selectList(qw);
        students.forEach(student -> System.out.println(student));
    }

23、order :指定字段和排序方向

/**
     * order :指定字段和排序方向
     *
     * boolean condition : 条件内容是否加入到 sql语句的后面。
     * true:条件加入到sql语句
     * FROM student ORDER BY name ASC
     *
     * false:条件不加入到sql语句
     * FROM student
     */
    @Test
    public void testOrder(){
        QueryWrapper<Student> qw = new QueryWrapper<>();
        qw.orderBy(true,true,"name")
                .orderBy(true,false,"age")
                .orderBy(true,false,"email");
        // name asc, age desc , email desc
        //FROM student ORDER BY name ASC , age DESC , email DESC
        List<Student> students = studentMapper.selectList(qw);
        students.forEach(student -> System.out.println(student));
    }

24、and ,or

/**
     * and ,or方法
     */
    @Test
    public void testOr(){
        QueryWrapper<Student> qw= new QueryWrapper<>();
        //WHERE name = ? OR age = ?
        qw.eq("name","张三")
                .or()
                .eq("age",22);
        List<Student> students = studentMapper.selectList(qw);
        students.forEach(student -> System.out.println(student));
    }

25、last : 拼接sql语句到MP的sql语句的最后

/**
     * last : 拼接sql语句到MP的sql语句的最后
     */
    @Test
    public void testLast(){
        QueryWrapper<Student> qw = new QueryWrapper<>();
        //SELECT id,name,age,email,status FROM student WHERE name = ? OR age = ? limit 1
        qw.eq("name","张三")
                .or()
                .eq("age",22)
                .last("limit 1");
        List<Student> students = studentMapper.selectList(qw);
        students.forEach(student -> System.out.println(student));
    }

26、exists : 判断条件

/**
     * exists : 判断条件
     *
     * notExists
     */
    @Test
    public void testExists(){
        QueryWrapper<Student> qw= new QueryWrapper<>();
        //SELECT id,name,age,email,status FROM student
        // WHERE EXISTS (select id from student where age > 20)
        //qw.exists("select id from student where age > 90");

        //SELECT id,name,age,email,status FROM student WHERE
        // NOT EXISTS (select id from student where age > 90)

        qw.notExists("select id from student where age > 90");
        List<Student> students = studentMapper.selectList(qw);
        students.forEach(student -> System.out.println(student));
    }

二、分页

分页插件 | MyBatis-Plus

1、配置分页,实现物理分页(默认内存分页)

/**
 * @Configuration: 标注的类就相当于xml配置文件
 */
@Configuration
public class Config {

    /***
     * 定义方法,返回的返回值是java 对象,这个对象是放入到spring容器中
     * 使用@Bean修饰方法
     * @Bean 等同于<bean></bean>
     */
    @Bean
    public PaginationInnerInterceptor paginationInnerInterceptor(){
        return new PaginationInnerInterceptor();
    }
}

2、 测试

/**
     * 分页:
     * 1.统计记录数,使用count(1)
     *    SELECT COUNT(1) FROM student WHERE age > ?
     * 2.实现分页,在sql语句的末尾加入 limit 0,3
     *    SELECT id,name,age,email,status FROM student WHERE age > ? LIMIT 0,3
     */
    @Test
    public void testPage(){
        QueryWrapper<Student> qw = new QueryWrapper<>();
        qw.gt("age",22);

        IPage<Student> page  = new Page<>();
        //设置分页的数据
        page.setCurrent(1);//第一页
        page.setSize(3);// 每页的记录数

        IPage<Student> result = studentMapper.selectPage(page,qw);

        //获取分页后的记录
        List<Student> students = result.getRecords();
        System.out.println("students.size()="+students.size());

        //分页的信息
        long pages  = result.getPages();
        System.out.println("页数:"+pages);
        System.out.println("总记录数:"+result.getTotal());
        System.out.println("当前页码:"+result.getCurrent());
        System.out.println("每页的记录数:"+result.getSize());
    }

三、MP代码生成器

代码生成器(旧) | MyBatis-Plus

代码生成器(新) | MyBatis-Plus

AutoGenerator 是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各个模块的代码,极大的提升了开发效率 

1、添加依赖

<!-- MyBatis-Plus 从 3.0.3 之后移除了代码生成器与模板引擎的默认依赖,需要手动添加相关依赖
            添加 代码生成器 依赖 mybatis-plus-generator
            添加 模板引擎 依赖,MyBatis-Plus 支持 Velocity(默认)、Freemarker、Beetl,用户可以选择自己熟悉的模板引擎,如果都不满足要求,可以采用自定义模板引擎
            Velocity(默认)  velocity-engine-core
        -->

        <!-- 模板引擎 -->
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.0</version>
        </dependency>

        <!-- mybatis-plus代码生成器 -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.3.0</version>
        </dependency>

2、自动生成类

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

public class AutoMapper {
    public static void main(String[] args) {
        //创建AutoGenerator ,MP中对象
        AutoGenerator ag = new AutoGenerator();

        /**-------- 设置全局配置 --------*/
        GlobalConfig gc  = new GlobalConfig();
        //设置代码的生成位置, 磁盘的目录
        String path = System.getProperty("user.dir");
        gc.setOutputDir(path+"/src/main/java");
        //设置生成的类的名称(命名规则)
        gc.setMapperName("%sMapper");//所有的Dao类都是Mapper结尾的,例如DeptMapper
        //设置Service接口的命名
        gc.setServiceName("%sService");//DeptService
        //设置Service实现类的名称
        gc.setServiceImplName("%sServiceImpl");//DeptServiceImpl
        //设置Controller类的命名
        gc.setControllerName("%sController");//DeptController
        //设置作者
        gc.setAuthor("ming");
        //设置主键id的配置
        gc.setIdType(IdType.ASSIGN_ID);
        ag.setGlobalConfig(gc);

        /**-------- 设置数据源DataSource --------*/
        DataSourceConfig ds = new DataSourceConfig();
        //驱动
        ds.setDriverName("com.mysql.cj.jdbc.Driver");
        //设置url
        ds.setUrl("jdbc:mysql://localhost:3306/mybatisplusdb");
        //设置数据库的用户名
        ds.setUsername("root");
        //设置密码
        ds.setPassword("admin123456");
        //把DataSourceConfig赋值给AutoGenerator
        ag.setDataSource(ds);

         /**-------- 设置Package信息 --------*/
        PackageConfig pc  = new PackageConfig();
        //设置模块名称, 相当于包名, 在这个包的下面有 mapper, service, controller。
        pc.setModuleName("user");
        //设置父包名,order就在父包的下面生成
        pc.setParent("com.company"); //com.company.user
        ag.setPackageInfo(pc);

         /**-------- 设置策略 --------*/
        StrategyConfig sc  = new StrategyConfig();
        sc.setNaming(NamingStrategy.underline_to_camel);
        //设置支持驼峰的命名规则
        sc.setColumnNaming(NamingStrategy.underline_to_camel);
        ag.setStrategy(sc);

        //执行代码的生成
        ag.execute();
    }
}

可能会报错

mp 报错‘AutoGenerator ()‘ has private access in ‘com.baomidou.mybatisplus.generator.AutoGenerator‘

我用的 mybatis-plus-generator 依赖 是 3.5.0,我用的 mybatis-Plus 依赖版本是 3.5.1, 在网上查了下,应该就是版本问题,后来我把 mybatis-plus-generator 依赖 换成 3.3.0 即可

生成完成,且会自动打开生成文件所在文件夹

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值