MyBatista Plus笔记-01

MyBatista Plus笔记-01

第1章 介绍和快速入门

1-1 官方文档

https://mp.baomidou.com/

1-5 快速入门案例

https://mp.baomidou.com/guide/quick-start.html#%E5%88%9D%E5%A7%8B%E5%8C%96%E5%B7%A5%E7%A8%8B

第2章 基本使用

2-1 新增方法

  • insert(T)

2-2 常用注解

https://mp.baomidou.com/guide/annotation.html#tablefield

2-3 排除非表中字段的三种方式

private transient String remark;
private static String remark;
    @TableField(exist = true)
    private static String remark;

第3章 查询方法

3-1 普通查询

package io.github.talelin.merak.mapper;

import io.github.talelin.merak.entity.MpDemoUser;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import static org.junit.Assert.*;

@RunWith(SpringRunner.class)
@SpringBootTest
public class MpDemoUserMapperTest {

    @Resource
    private MpDemoUserMapper mapper;


    @Test
    public void selectById(){
//        MpDemoUser user = mapper.selectById(10000L);// 不存在返回null

        MpDemoUser user1 = mapper.selectById(1087982257332887553L);
        System.out.println(user1);
    }
    @Test
    public void selectBatchIds(){

//        数组中有错的也没事,不会报错
        List<Long> longs = Arrays.asList(1087982257332887553L, 12343452346L, 1088248166370832385L);
        List<MpDemoUser> users = mapper.selectBatchIds(longs);

        System.out.println(users);
    }

    @Test
    public void selectByMap(){
        HashMap<String, Object> stringStringHashMap = new HashMap<>();
        stringStringHashMap.put("name", "大boss");
        List<MpDemoUser> users = mapper.selectByMap(stringStringHashMap);

        System.out.println(users);
    }

}

3-2 条件构造器查询(1)

package io.github.talelin.merak.mapper;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.github.talelin.merak.entity.MpDemoUser;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * 条件构造器查询
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class WrapperTest1 {

    @Resource
    private MpDemoUserMapper mapper;


    /**
     * 查询的时候一般用queryWrapper
     * 更新用UpdateWrapper
     * <p>
     * 1、名字中包含雨并且年龄小于40
     * name like '%雨%' and age<40
     */
    @Test
    public void selectByWrapper() {

//        两种构造方式,第二种写起来感觉怪怪的
        QueryWrapper<MpDemoUser> wrapper1 = new QueryWrapper<>();
        QueryWrapper<MpDemoUser> wrapper2 = Wrappers.<MpDemoUser>query();
//        QueryWrapper<MpDemoUser> q = wrapper1.like("雨","name");
        QueryWrapper<MpDemoUser> qw1 = wrapper1.like("name", "雨").lt("age", 40);
        QueryWrapper<MpDemoUser> qw2 = wrapper1.like("name", "雨").and(s -> s.lt("age", 40));


        List<MpDemoUser> users = mapper.selectList(qw1);
        System.out.println(users);
    }


    /**
     * 2、名字中包含雨年并且龄大于等于20且小于等于40并且email不为空
     * name like '%雨%' and age between 20 and 40 and email is not null
     */
    @Test
    public void selectByWrapper2() {

        QueryWrapper<MpDemoUser> wrapper1 = new QueryWrapper<>();
        QueryWrapper<MpDemoUser> wrapper2 = Wrappers.<MpDemoUser>query();

        QueryWrapper<MpDemoUser> qw = wrapper2.like("name", "雨").between("age", 20, 40).isNotNull("email");

        List<MpDemoUser> users = mapper.selectList(qw);
        System.out.println(users);
    }


    /**
     *3、名字为王姓或者年龄大于等于25,按照年龄降序排列,年龄相同按照id升序排列
     *      name like '王%' or age>=25 order by age desc,id asc
     */
    @Test
    public void selectByWrapper3() {

        QueryWrapper<MpDemoUser> wrapper1 = new QueryWrapper<>();
        QueryWrapper<MpDemoUser> wrapper2 = Wrappers.<MpDemoUser>query();

        QueryWrapper<MpDemoUser> qw = wrapper1
                .likeRight("name", "王")
                .or(s->s.ge("age",25))
                .orderByDesc("age")
                .orderByAsc("id");


        QueryWrapper<MpDemoUser> qw2 = wrapper1
                .likeRight("name", "王")
                .or()
                .ge("age",25)
                .orderByDesc("age")
                .orderByAsc("id");

        List<MpDemoUser> users = mapper.selectList(qw);
        System.out.println(users);
    }


}

3-3 条件构造器查询(2)

3-4 条件构造器查询(3)

3-5 条件构造器查询(4)

package io.github.talelin.merak.mapper;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.github.talelin.merak.entity.MpDemoUser;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * 条件构造器查询
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class WrapperTest1 {

    @Resource
    private MpDemoUserMapper mapper;


    /**
     * 查询的时候一般用queryWrapper
     * 更新用UpdateWrapper
     * <p>
     * 1、名字中包含雨并且年龄小于40
     * name like '%雨%' and age<40
     */
    @Test
    public void selectByWrapper() {

//        两种构造方式,第二种写起来感觉怪怪的
        QueryWrapper<MpDemoUser> wrapper1 = new QueryWrapper<>();
        QueryWrapper<MpDemoUser> wrapper2 = Wrappers.<MpDemoUser>query();
//        QueryWrapper<MpDemoUser> q = wrapper1.like("雨","name");
        QueryWrapper<MpDemoUser> qw1 = wrapper1.like("name", "雨").lt("age", 40);
        QueryWrapper<MpDemoUser> qw2 = wrapper1.like("name", "雨").and(s -> s.lt("age", 40));


        List<MpDemoUser> users = mapper.selectList(qw1);
        System.out.println(users);
    }


    /**
     * 2、名字中包含雨年并且龄大于等于20且小于等于40并且email不为空
     * name like '%雨%' and age between 20 and 40 and email is not null
     */
    @Test
    public void selectByWrapper2() {

        QueryWrapper<MpDemoUser> wrapper1 = new QueryWrapper<>();
        QueryWrapper<MpDemoUser> wrapper2 = Wrappers.<MpDemoUser>query();

        QueryWrapper<MpDemoUser> qw = wrapper2.like("name", "雨").between("age", 20, 40).isNotNull("email");

        List<MpDemoUser> users = mapper.selectList(qw);
        System.out.println(users);
    }


    /**
     * 3、名字为王姓或者年龄大于等于25,按照年龄降序排列,年龄相同按照id升序排列
     * name like '王%' or age>=25 order by age desc,id asc
     */
    @Test
    public void selectByWrapper3() {

        QueryWrapper<MpDemoUser> wrapper1 = new QueryWrapper<>();
        QueryWrapper<MpDemoUser> wrapper2 = Wrappers.<MpDemoUser>query();

        QueryWrapper<MpDemoUser> qw = wrapper1
                .likeRight("name", "王")
                .or(s -> s.ge("age", 25))
                .orderByDesc("age")
                .orderByAsc("id");


        QueryWrapper<MpDemoUser> qw2 = wrapper1
                .likeRight("name", "王")
                .or()
                .ge("age", 25)
                .orderByDesc("age")
                .orderByAsc("id");

        List<MpDemoUser> users = mapper.selectList(qw);
        System.out.println(users);
    }


    /**
     * 4、创建日期为2019年2月14日并且直属上级为名字为王姓
     * date_format(create_time,'%Y-%m-%d')='2019-02-14' and manager_id in (select id from user where name like '王%')
     * <p>
     * <p>
     * <p>
     * apply
     * apply(String applySql, Object... params)
     * apply(boolean condition, String applySql, Object... params)
     * 拼接 sql
     * 注意事项:
     * <p>
     * 该方法可用于数据库函数 动态入参的params对应前面applySql内部的{index}部分.这样是不会有sql注入风险的,反之会有!
     * <p>
     * 例: apply("id = 1")--->id = 1
     * 例: apply("date_format(dateColumn,'%Y-%m-%d') = '2008-08-08'")--->date_format(dateColumn,'%Y-%m-%d') = '2008-08-08'")
     * 例: apply("date_format(dateColumn,'%Y-%m-%d') = {0}", "2008-08-08")--->date_format(dateColumn,'%Y-%m-%d') = '2008-08-08'")
     */
    @Test
    public void selectByWrapper4() {

        QueryWrapper<MpDemoUser> wrapper1 = new QueryWrapper<>();
        QueryWrapper<MpDemoUser> wrapper2 = Wrappers.<MpDemoUser>query();

        QueryWrapper<MpDemoUser> qw = wrapper1
                .apply("date_format(create_time,'%Y-%m-%d') = {0}", "2019-02-14")
                .inSql("manager_id", "select id from mp_demo_user where name like '王%'");

        List<MpDemoUser> users = mapper.selectList(qw);
        System.out.println(users);
    }


    /**
     * 5、名字为王姓并且(年龄小于40或邮箱不为空)
     * name like '王%' and (age<40 or email is not null)
     * <p>
     * #nested
     * nested(Consumer<Param> consumer)
     * nested(boolean condition, Consumer<Param> consumer)
     * 正常嵌套 不带 AND 或者 OR
     * 例: nested(i -> i.eq("name", "李白").ne("status", "活着"))--->(name = '李白' and status <> '活着')
     * #apply
     */
    @Test
    public void selectByWrapper5() {

        QueryWrapper<MpDemoUser> wrapper1 = new QueryWrapper<>();
        QueryWrapper<MpDemoUser> wrapper2 = Wrappers.<MpDemoUser>query();

        QueryWrapper<MpDemoUser> qw = wrapper1
                .likeRight("name", "王")
                .nested(item -> item.lt("age", 40).or().isNotNull("email"));

        List<MpDemoUser> users = mapper.selectList(qw);
        System.out.println(users);
    }


    /**
     * 6、名字为王姓或者(年龄小于40并且年龄大于20并且邮箱不为空)
     * name like '王%' or (age<40 and age>20 and email is not null)
     */
    @Test
    public void selectByWrapper6() {

        QueryWrapper<MpDemoUser> wrapper1 = new QueryWrapper<>();
        QueryWrapper<MpDemoUser> wrapper2 = Wrappers.<MpDemoUser>query();

        QueryWrapper<MpDemoUser> qw = wrapper1
                .likeRight("name", "王")
                .or(item -> item.between("age", 20, 40).isNotNull("email"));

        QueryWrapper<MpDemoUser> qw2 = wrapper1
                .likeRight("name", "王")
                .or(item -> item.gt("age", 20).lt("age", 40).isNotNull("email"));


        List<MpDemoUser> users = mapper.selectList(qw);
        System.out.println(users);
    }


    /**
     *7、(年龄小于40或邮箱不为空)并且名字为王姓
     *     (age<40 or email is not null) and name like '王%'
     */
    @Test
    public void selectByWrapper7() {

        QueryWrapper<MpDemoUser> wrapper1 = new QueryWrapper<>();
        QueryWrapper<MpDemoUser> wrapper2 = Wrappers.<MpDemoUser>query();

        QueryWrapper<MpDemoUser> qw = wrapper1
                .nested(item -> item.lt("age", 40).or().isNotNull("email"))
                .likeRight("name", "王");


        List<MpDemoUser> users = mapper.selectList(qw);
        System.out.println(users);
    }
    /**
     *8、年龄为30、31、34、35
     *     age in (30、31、34、35)
     *
     */
    @Test
    public void selectByWrapper8() {

        QueryWrapper<MpDemoUser> wrapper1 = new QueryWrapper<>();
        QueryWrapper<MpDemoUser> wrapper2 = Wrappers.<MpDemoUser>query();

        List<Integer> list = Arrays.asList(30, 31, 32, 33, 34, 35);
        QueryWrapper<MpDemoUser> qw = wrapper1
                .in("age", list);



        List<MpDemoUser> users = mapper.selectList(qw);
        System.out.println(users);
    }



    /**
     * 9、只返回满足条件的其中一条语句即可
     * limit 1
     */
    @Test
    public void selectByWrapper9() {

        QueryWrapper<MpDemoUser> wrapper1 = new QueryWrapper<>();
        QueryWrapper<MpDemoUser> wrapper2 = Wrappers.<MpDemoUser>query();

        List<Integer> list = Arrays.asList(30, 31, 32, 33, 34, 35);
        QueryWrapper<MpDemoUser> qw = wrapper1
                .in("age", list)
                .last("limit 1");



        List<MpDemoUser> users = mapper.selectList(qw);
        System.out.println(users);
    }




}

3-6 select不列出全部字段

package io.github.talelin.merak.mapper;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.github.talelin.merak.entity.MpDemoUser;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * 条件构造器查询
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class WrapperTest2 {

    @Resource
    private MpDemoUserMapper mapper;


    /**
     * select中字段不全部出现的查询
     * 10、名字中包含雨并且年龄小于40(需求1加强版)
     * 第一种情况:select id,name
     * 	           from user
     * 	           where name like '%雨%' and age<40
     * 第二种情况:select id,name,age,email
     * 	           from user
     * 	           where name like '%雨%' and age<40
     *
     */
    @Test
    public void selectByWrapper10() {

        QueryWrapper<MpDemoUser> wrapper1 = new QueryWrapper<>();
        QueryWrapper<MpDemoUser> wrapper2 = Wrappers.<MpDemoUser>query();

        QueryWrapper<MpDemoUser> qw1 = wrapper1
                .like("name", "雨")
                .lt("age", 40)
                .select("id", "name");


        QueryWrapper<MpDemoUser> qw2 = wrapper1
                .like("name", "雨")
                .lt("age", 40)
                .select(MpDemoUser.class, item -> !item.getColumn().equals("create_time") && !item.getColumn().equals("manager_id"));

        List<MpDemoUser> users = mapper.selectList(qw1);
        System.out.println(users);
    }



}

3-7 condition作用

    /**
     * LIKE '%值%'
     *
     * @param condition 执行条件
     * @param column    字段
     * @param val       值
     * @return children
     */
    Children like(boolean condition, R column, Object val);

如果是false就不会拼接这个子句。

之前我们如果遇到字段名称没有的时候,我们会写两条语句来实现这个查询

现在只需要一条就行了。

一般这样用

wrapper1.like(StringUtils.isEmpty(username), "name", "王");

3-8 实体作为条件构造器构造方法的参数

package io.github.talelin.merak.mapper;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.github.talelin.merak.entity.MpDemoUser;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * 条件构造器查询
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class WrapperTest2 {

    @Resource
    private MpDemoUserMapper mapper;

    /**
     * Preparing: SELECT id,name,age,email,manager_id,create_time,update_time,version,deleted
     * FROM mp_demo_user
     * WHERE name=? AND deleted=0 
     */
    @Test
    public void selectByWrapperEntity() {
        MpDemoUser user = new MpDemoUser();
        user.setName("王大大");

        QueryWrapper<MpDemoUser> wrapper = new QueryWrapper<>(user);

        List<MpDemoUser> users = mapper.selectList(wrapper);
        System.out.println(users);
    }






}

3-9 AllEq用法

package io.github.talelin.merak.mapper;

import com.amdelamar.jhash.Hash;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.github.talelin.merak.entity.MpDemoUser;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * 条件构造器查询
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class WrapperTest2 {

    @Resource
    private MpDemoUserMapper mapper;

    /**
     *allEq
     * Preparing: SELECT id,name,age,email,manager_id,create_time,update_time,version,deleted
     * FROM mp_demo_user
     * WHERE deleted=0 AND (name = ?)
     */
    @Test
    public void selectByWrapperAllEq() {

        QueryWrapper<MpDemoUser> wrapper = new QueryWrapper<>();
        HashMap<String, Object> map = new HashMap<>();
        map.put("name", "王大大");

        QueryWrapper<MpDemoUser> wrapper1 = wrapper.allEq(map);
//        QueryWrapper<MpDemoUser> wrapper1 = wrapper.allEq(map,true); //对null的忽略拼接SQL

        List<MpDemoUser> users = mapper.selectList(wrapper1);
        System.out.println(users);
    }


}

3-10 其他使用条件构造器的方法

  • List<Map<String, Object>> selectMaps(@Param(Constants.WRAPPER) Wrapper queryWrapper);

    使用场景是:我们查询实体部分字段的时候,其他字段都是null,

    这时候我们只需要返回一个需要字段组成的map就行了。

    package io.github.talelin.merak.mapper;
    
    import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
    import com.baomidou.mybatisplus.core.toolkit.Wrappers;
    import io.github.talelin.merak.entity.MpDemoUser;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.test.context.junit4.SpringRunner;
    
    import javax.annotation.Resource;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    /**
     * 条件构造器查询
     */
    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class WrapperTest3 {
    
        @Resource
        private MpDemoUserMapper mapper;
    
    
        /**
         * select中字段不全部出现的查询
         * 10、名字中包含雨并且年龄小于40(需求1加强版)
         *
         *      * 根据 Wrapper 条件,查询全部记录
         *      *
         *      * @param queryWrapper 实体对象封装操作类(可以为 null)
         *
         *    List<Map<String, Object>> selectMaps(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
         *
         *
         */
        @Test
        public void selectByWrapperMaps() {
    
            QueryWrapper<MpDemoUser> wrapper1 = new QueryWrapper<>();
            QueryWrapper<MpDemoUser> wrapper2 = Wrappers.<MpDemoUser>query();
    
            QueryWrapper<MpDemoUser> qw1 = wrapper1
                    .select("name","age")
                    .like("name", "雨");
    
            List<Map<String, Object>> maps = mapper.selectMaps(qw1);
    
            System.out.println(maps);
        }
    
    
    
    }
    
    2020-03-18 18:54:28.700 DEBUG 11448 --- [           main] i.g.t.m.m.MpDemoUserMapper.selectMaps    : ==>  Preparing: SELECT name,age FROM mp_demo_user WHERE deleted=0 AND (name LIKE ?) 
    2020-03-18 18:54:28.700 DEBUG 11448 --- [           main] i.g.t.m.m.MpDemoUserMapper.selectMaps    : ==> Parameters: %雨%(String)
    2020-03-18 18:54:28.701 DEBUG 11448 --- [           main] i.g.t.m.m.MpDemoUserMapper.selectMaps    : <==      Total: 3
    [{name=张雨琪, age=31}, {name=刘红雨, age=32}, {name=雨狗蛋, age=12}]
    
  • slectMaps 可以实现一些查询结果的分组 聚合统计操作

    package io.github.talelin.merak.mapper;
    
    import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
    import com.baomidou.mybatisplus.core.toolkit.Wrappers;
    import io.github.talelin.merak.entity.MpDemoUser;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.test.context.junit4.SpringRunner;
    
    import javax.annotation.Resource;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    /**
     * 条件构造器查询
     */
    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class WrapperTest3 {
    
        @Resource
        private MpDemoUserMapper mapper;
        /**
         * 三、统计查询:
         * 11、按照直属上级分组,查询每组的平均年龄、最大年龄、最小年龄。
         * 并且只取年龄总和小于500的组。
         * select avg(age) avg_age,min(age) min_age,max(age) max_age
         * from user
         * group by manager_id
         * having sum(age) <500
         */
        @Test
        public void selectByWrapper11() {
    
            QueryWrapper<MpDemoUser> wrapper1 = new QueryWrapper<>();
            QueryWrapper<MpDemoUser> wrapper2 = Wrappers.<MpDemoUser>query();
    
            QueryWrapper<MpDemoUser> qw1 = wrapper1
                    .select("avg(age) avg_age", "min(age) min_age", "max(age) max_age")
                    .groupBy("manager_id")
                    .having("sum(age) < {0}", 500);
    
            List<Map<String, Object>> maps = mapper.selectMaps(qw1);
            System.out.println(maps);
        }
    
    }
    
    2020-03-18 18:59:58.389 DEBUG 11604 --- [           main] i.g.t.m.m.MpDemoUserMapper.selectMaps    : ==>  Preparing: SELECT avg(age) avg_age,min(age) min_age,max(age) max_age FROM mp_demo_user WHERE deleted=0 GROUP BY manager_id HAVING sum(age) < ? 
    2020-03-18 18:59:58.390 DEBUG 11604 --- [           main] i.g.t.m.m.MpDemoUserMapper.selectMaps    : ==> Parameters: 500(Integer)
    2020-03-18 18:59:58.392 DEBUG 11604 --- [           main] i.g.t.m.m.MpDemoUserMapper.selectMaps    : <==      Total: 3
    [{max_age=40, avg_age=25.6667, min_age=12}, {max_age=25, avg_age=25.0000, min_age=25}, {max_age=32, avg_age=30.3333, min_age=28}]
    
    
  • /**
     * 根据 Wrapper 条件,查询全部记录
     * <p>注意: 只返回第一个字段的值</p>
     *
     * @param queryWrapper 实体对象封装操作类(可以为 null)
     */
    List<Object> selectObjs(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
    
  • 计数

        /**
         * 根据 Wrapper 条件,查询总记录数
         *
         * @param queryWrapper 实体对象封装操作类(可以为 null)
         * Integer selectCount(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
         */
        @Test
        public void selectByWrapperCount() {
    
            QueryWrapper<MpDemoUser> wrapper = new QueryWrapper<>();
    
            QueryWrapper<MpDemoUser> wrapper1 = wrapper.like("name", "王");
    
            Integer count = mapper.selectCount(wrapper1);
            System.out.println(count);
        }
    
    
    2020-03-18 19:06:27.543 DEBUG 11789 --- [           main] i.g.t.m.m.MpDemoUserMapper.selectCount   : ==>  Preparing: SELECT COUNT( 1 ) FROM mp_demo_user WHERE deleted=0 AND (name LIKE ?) 
    2020-03-18 19:06:27.544 DEBUG 11789 --- [           main] i.g.t.m.m.MpDemoUserMapper.selectCount   : ==> Parameters: %王%(String)
    2020-03-18 19:06:27.545 DEBUG 11789 --- [           main] i.g.t.m.m.MpDemoUserMapper.selectCount   : <==      Total: 1
    2
    
    
  • selectOne 注意查不出来返回null,查到多个报错

       /**
         /**
         * 根据 entity 条件,查询一条记录
         *
         * @param queryWrapper 实体对象封装操作类(可以为 null)
         *  T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
         *                
         */
        @Test
        public void selectByWrapperOne() {
    
            QueryWrapper<MpDemoUser> wrapper = new QueryWrapper<>();
    
            QueryWrapper<MpDemoUser> wrapper1 = wrapper.eq("name", "王大大");
    
            MpDemoUser user = mapper.selectOne(wrapper1);
            System.out.println(user);
        }
    

3-11 lambda条件构造器

    /**
     * LambdaQueryWrapper可以防止字段输入错误
     */
    @Test
    public void selectLambda() {


        LambdaQueryWrapper<MpDemoUser> lambdaQueryWrapper1 = new QueryWrapper<MpDemoUser>().lambda();
        LambdaQueryWrapper<MpDemoUser> lambdaQueryWrapper2 = new LambdaQueryWrapper<MpDemoUser>();
        LambdaQueryWrapper<MpDemoUser> lambdaQueryWrapper3 = Wrappers.lambdaQuery(MpDemoUser.class);


//        QueryWrapper<MpDemoUser> wrapper1 = Wrappers.<MpDemoUser>query();
//
//        QueryWrapper<MpDemoUser> qw1 = wrapper1
//                .like("name", "雨")
//                .lt("age", 40)
//                .select("id", "name");


        LambdaQueryWrapper<MpDemoUser> wr = lambdaQueryWrapper1
                .like(MpDemoUser::getName, "雨")
                .lt(MpDemoUser::getAge, 40)
                .select(MpDemoUser::getId, MpDemoUser::getName);


        List<MpDemoUser> users = mapper.selectList(wr);
        System.out.println(users);
    }

第4章 自定义sql及分页查询

本章介绍MyBatis-Plus中自定义sql和分页查询的内容。

4-1 自定义sql

又想使用条件构造器,又想自定义sql咋办

package io.github.talelin.merak.mapper;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import io.github.talelin.merak.entity.MpDemoUser;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * @author allen
 */
public interface MpDemoUserMapper extends BaseMapper<MpDemoUser> {


    /**
     * @param wrapper
     * @return
     */
    @Select("select * from mp_demo_user")
    List<MpDemoUser> findAllUser(@Param(Constants.WRAPPER) Wrapper<MpDemoUser> wrapper);
}

或者使用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="io.github.talelin.merak.mapper.MpDemoUserMapper">

    <select id="findAllUser" resultType="io.github.talelin.merak.entity.MpDemoUser">
                select * from mp_demo_user 
    </select>


</mapper>
    @Test
    public void selectMy() {
        LambdaQueryWrapper<MpDemoUser> lambdaQueryWrapper1 = new QueryWrapper<MpDemoUser>().lambda();
//
        List<MpDemoUser> allUser = mapper.findAllUser(lambdaQueryWrapper1);
        System.out.println(allUser);
    }

4-2 分页查询

    @Test
    public void selectPage() {

        QueryWrapper<MpDemoUser> wrapper1 = new QueryWrapper<>();

        QueryWrapper<MpDemoUser> qw1 = wrapper1
                .select("name","age")
                .like("name", "雨");

        Page<MpDemoUser> page = new Page<MpDemoUser>(1,2);

        Page<MpDemoUser> res = mapper.selectPage(page, null);
//        IPage<MpDemoUser> mpDemoUserPage = mpDemoUserPage1

        System.out.println(res);
    }

image-20200318201437842

第5章 更新及删除

介绍MyBatis-Plus中更新和删除功能的使用。

5-1 更新方法

 @Test
    public void update() {

        MpDemoUser user = new MpDemoUser();
        user.setId(1240100589369425925L);
        user.setName("王大大22");

        int res = mapper.updateById(user);


        System.out.println(res);
    }

    @Test
    public void updateByWrapper1() {

        LambdaUpdateWrapper<MpDemoUser> wrapper = new LambdaUpdateWrapper<>();
        LambdaUpdateWrapper<MpDemoUser> query = wrapper.eq(MpDemoUser::getId, "1240100589369425925");
        MpDemoUser user = new MpDemoUser();
        user.setEmail("王大大@33.com");

        int res = mapper.update(user, query);


        System.out.println(res);
    }

    /**
     * 上面的需要创建一个空的对象,不够优雅
     *   * 根据 whereEntity 条件,更新记录
     *      *
     *      * @param entity        实体对象 (set 条件值,可以为 null)
     *      * @param updateWrapper 实体对象封装操作类(可以为 null,里面的 entity 用于生成 where 语句)
     */
    @Test
    public void updateByWrapper2() {

        LambdaQueryWrapper<MpDemoUser> objectLambdaQueryWrapper = Wrappers.lambdaQuery();
        LambdaUpdateWrapper<MpDemoUser> wrapper = new LambdaUpdateWrapper<>();
        LambdaUpdateWrapper<MpDemoUser> query = wrapper
                .eq(MpDemoUser::getId, "1240100589369425925")
                .set(MpDemoUser::getName, "王小小");

        int res = mapper.update(null, query);


        System.out.println(res);
    }

5-2 删除方法

  @Test
    public void deleteByList() {

        LambdaQueryWrapper<MpDemoUser> wrapper = Wrappers.lambdaQuery();

        LambdaQueryWrapper<MpDemoUser> query = wrapper.like(MpDemoUser::getName, "雨");
        List<Object> objects = mapper.selectObjs(query);
        System.out.println(objects);

        List<Long> collect = objects.stream().map(item -> Long.valueOf(String.valueOf(item))).collect(Collectors.toList());

        int i = mapper.deleteBatchIds(collect);
        System.out.println(i);


    }
    @Test
    public void deleteByWrapper() {

        LambdaQueryWrapper<MpDemoUser> wrapper = Wrappers.lambdaQuery();

        LambdaQueryWrapper<MpDemoUser> query = wrapper.like(MpDemoUser::getName, "雨");


        int delete = mapper.delete(query);
        System.out.println(delete);


    }

第6章 AR模式、主键策略和基本配置

本章介绍MyBatis-Plus中的AR模式、主键策略和基本配置等内容。

6-1 AR模式

AR模式类似于django中的ORM,一个模型类具备CURD的功能

package io.github.talelin.merak.entity;

import com.baomidou.mybatisplus.annotation.*;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import lombok.Data;
import lombok.EqualsAndHashCode;

import java.util.Date;


/**
 * (MpDemoUser)实体类
 *
 * @author makejava
 * @since 2020-03-18 09:56:00
 */
@TableName("mp_demo_user")
@Data
public class MpDemoUser extends Model<MpDemoUser> {
    /**
     * 主键
     */
    @TableId(value = "id", type = IdType.NONE)  //默认的 NONE
    private Long id;
    /**
     * 姓名
     */
    private String name;
    /**
     * 年龄
     */
    private Integer age;
    /**
     * 邮箱
     */
    private String email;
    /**
     * 直属上级id
     */
    private Long managerId;
    /**
     * 创建时间
     * 需要自动填充
     */
    @TableField(fill = FieldFill.UPDATE)
    private Date createTime;
    /**
     * 修改时间
     * 需要自动填充
     */
    @TableField(fill = FieldFill.INSERT)
    private Date updateTime;
    /**
     * 版本
     */
    private Integer version;
    /**
     * 逻辑删除标识(0.未删除,1.已删除)
     * 需要配置逻辑删除
     */

    @TableLogic(value = "0", delval = "1")
    private Integer deleted;


    @TableField(exist = true)
    private static String remark;


}

package io.github.talelin.merak.mapper;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.github.talelin.merak.entity.MpDemoUser;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 条件构造器查询
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class ARTest5 {

    @Resource
    private MpDemoUserMapper mapper;



    @Test
    public void arTest() {

        QueryWrapper<MpDemoUser> wrapper1 = new QueryWrapper<>();

        QueryWrapper<MpDemoUser> qw1 = wrapper1
                .like("name", "雨");



        MpDemoUser user = new MpDemoUser();
        Integer count = user.selectCount(qw1);
        System.out.println(count);

    }


}

其他的API看源码就好

6-2 主键策略

@TableId

  • 描述:主键注解
属性类型必须指定默认值描述
valueString“”主键字段名
typeEnumIdType.NONE主键类型
#IdType
描述
AUTO数据库ID自增
NONE无状态,该类型为未设置主键类型(注解里等于跟随全局,全局里约等于 INPUT)
INPUTinsert前自行set主键值
ASSIGN_ID分配ID(主键类型为Number(Long和Integer)或String)(since 3.3.0),使用接口IdentifierGenerator的方法nextId(默认实现类为DefaultIdentifierGenerator雪花算法)
ASSIGN_UUID分配UUID,主键类型为String(since 3.3.0),使用接口IdentifierGenerator的方法nextUUID(默认default方法)
ID_WORKER分布式全局唯一ID 长整型类型(please use ASSIGN_ID)
UUID32位UUID字符串(please use ASSIGN_UUID)
ID_WORKER_STR分布式全局唯一ID 字符串类型(please use ASSIGN_ID)

6-3 基本配置

https://mp.baomidou.com/config/#%E5%9F%BA%E6%9C%AC%E9%85%8D%E7%BD%AE

第7章 通用service

本章介绍通用service的内容。

7-1 通用service

定义service接口

package io.github.talelin.merak.service;

import com.baomidou.mybatisplus.extension.service.IService;
import io.github.talelin.merak.entity.MpDemoUser;

public interface MpDemoUserService extends IService<MpDemoUser> {
}

实现serviceImpl类

package io.github.talelin.merak.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.github.talelin.merak.entity.MpDemoUser;
import io.github.talelin.merak.mapper.MpDemoUserMapper;
import io.github.talelin.merak.service.MpDemoUserService;
import org.springframework.stereotype.Service;


/**
 * @author allen
 *
 * 通用service
 */
@Service
public class MpDemoUserServiceImpl extends ServiceImpl<MpDemoUserMapper, MpDemoUser> implements MpDemoUserService {

}

测试代码:

package io.github.talelin.merak.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import io.github.talelin.merak.entity.MpDemoUser;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;

import java.util.List;

import static org.junit.Assert.*;

@RunWith(SpringRunner.class)
@SpringBootTest
public class MpDemoUserServiceImplTest {

    @Resource
    private MpDemoUserServiceImpl service;


    @Test
    public void testService(){
        LambdaQueryWrapper<MpDemoUser> wrapper = Wrappers.lambdaQuery();
        MpDemoUser user = service.getOne(wrapper.like(MpDemoUser::getName, "雨"),false);
        System.out.println(user);
    }

    @Test
    public void testService2(){
        List<MpDemoUser> res = service.lambdaQuery().like(MpDemoUser::getName, "雨").list();
        System.out.println(res);
    }

}

通用service源码

/*
 * Copyright (c) 2011-2020, baomidou (jobob@qq.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * https://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.baomidou.mybatisplus.extension.service;

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.Assert;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.UpdateChainWrapper;
import com.baomidou.mybatisplus.extension.toolkit.ChainWrappers;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 顶级 Service
 *
 * @author hubin
 * @since 2018-06-23
 */
public interface IService<T> {

    /**
     * 默认批次提交数量
     */
    int DEFAULT_BATCH_SIZE = 1000;

    /**
     * 插入一条记录(选择字段,策略插入)
     *
     * @param entity 实体对象
     */
    default boolean save(T entity) {
        return SqlHelper.retBool(getBaseMapper().insert(entity));
    }

    /**
     * 插入(批量)
     *
     * @param entityList 实体对象集合
     */
    @Transactional(rollbackFor = Exception.class)
    default boolean saveBatch(Collection<T> entityList) {
        return saveBatch(entityList, DEFAULT_BATCH_SIZE);
    }

    /**
     * 插入(批量)
     *
     * @param entityList 实体对象集合
     * @param batchSize  插入批次数量
     */
    boolean saveBatch(Collection<T> entityList, int batchSize);

    /**
     * 批量修改插入
     *
     * @param entityList 实体对象集合
     */
    @Transactional(rollbackFor = Exception.class)
    default boolean saveOrUpdateBatch(Collection<T> entityList) {
        return saveOrUpdateBatch(entityList, DEFAULT_BATCH_SIZE);
    }

    /**
     * 批量修改插入
     *
     * @param entityList 实体对象集合
     * @param batchSize  每次的数量
     */
    boolean saveOrUpdateBatch(Collection<T> entityList, int batchSize);

    /**
     * 根据 ID 删除
     *
     * @param id 主键ID
     */
    default boolean removeById(Serializable id) {
        return SqlHelper.retBool(getBaseMapper().deleteById(id));
    }

    /**
     * 根据 columnMap 条件,删除记录
     *
     * @param columnMap 表字段 map 对象
     */
    default boolean removeByMap(Map<String, Object> columnMap) {
        Assert.notEmpty(columnMap, "error: columnMap must not be empty");
        return SqlHelper.retBool(getBaseMapper().deleteByMap(columnMap));
    }

    /**
     * 根据 entity 条件,删除记录
     *
     * @param queryWrapper 实体包装类 {@link com.baomidou.mybatisplus.core.conditions.query.QueryWrapper}
     */
    default boolean remove(Wrapper<T> queryWrapper) {
        return SqlHelper.retBool(getBaseMapper().delete(queryWrapper));
    }

    /**
     * 删除(根据ID 批量删除)
     *
     * @param idList 主键ID列表
     */
    default boolean removeByIds(Collection<? extends Serializable> idList) {
        if (CollectionUtils.isEmpty(idList)) {
            return false;
        }
        return SqlHelper.retBool(getBaseMapper().deleteBatchIds(idList));
    }

    /**
     * 根据 ID 选择修改
     *
     * @param entity 实体对象
     */
    default boolean updateById(T entity) {
        return SqlHelper.retBool(getBaseMapper().updateById(entity));
    }

    /**
     * 根据 UpdateWrapper 条件,更新记录 需要设置sqlset
     *
     * @param updateWrapper 实体对象封装操作类 {@link com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper}
     */
    default boolean update(Wrapper<T> updateWrapper) {
        return update(null, updateWrapper);
    }

    /**
     * 根据 whereEntity 条件,更新记录
     *
     * @param entity        实体对象
     * @param updateWrapper 实体对象封装操作类 {@link com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper}
     */
    default boolean update(T entity, Wrapper<T> updateWrapper) {
        return SqlHelper.retBool(getBaseMapper().update(entity, updateWrapper));
    }

    /**
     * 根据ID 批量更新
     *
     * @param entityList 实体对象集合
     */
    @Transactional(rollbackFor = Exception.class)
    default boolean updateBatchById(Collection<T> entityList) {
        return updateBatchById(entityList, DEFAULT_BATCH_SIZE);
    }

    /**
     * 根据ID 批量更新
     *
     * @param entityList 实体对象集合
     * @param batchSize  更新批次数量
     */
    boolean updateBatchById(Collection<T> entityList, int batchSize);

    /**
     * TableId 注解存在更新记录,否插入一条记录
     *
     * @param entity 实体对象
     */
    boolean saveOrUpdate(T entity);

    /**
     * 根据 ID 查询
     *
     * @param id 主键ID
     */
    default T getById(Serializable id) {
        return getBaseMapper().selectById(id);
    }

    /**
     * 查询(根据ID 批量查询)
     *
     * @param idList 主键ID列表
     */
    default List<T> listByIds(Collection<? extends Serializable> idList) {
        return getBaseMapper().selectBatchIds(idList);
    }

    /**
     * 查询(根据 columnMap 条件)
     *
     * @param columnMap 表字段 map 对象
     */
    default List<T> listByMap(Map<String, Object> columnMap) {
        return getBaseMapper().selectByMap(columnMap);
    }

    /**
     * 根据 Wrapper,查询一条记录 <br/>
     * <p>结果集,如果是多个会抛出异常,随机取一条加上限制条件 wrapper.last("LIMIT 1")</p>
     *
     * @param queryWrapper 实体对象封装操作类 {@link com.baomidou.mybatisplus.core.conditions.query.QueryWrapper}
     */
    default T getOne(Wrapper<T> queryWrapper) {
        return getOne(queryWrapper, true);
    }

    /**
     * 根据 Wrapper,查询一条记录
     *
     * @param queryWrapper 实体对象封装操作类 {@link com.baomidou.mybatisplus.core.conditions.query.QueryWrapper}
     * @param throwEx      有多个 result 是否抛出异常
     */
    T getOne(Wrapper<T> queryWrapper, boolean throwEx);

    /**
     * 根据 Wrapper,查询一条记录
     *
     * @param queryWrapper 实体对象封装操作类 {@link com.baomidou.mybatisplus.core.conditions.query.QueryWrapper}
     */
    Map<String, Object> getMap(Wrapper<T> queryWrapper);

    /**
     * 根据 Wrapper,查询一条记录
     *
     * @param queryWrapper 实体对象封装操作类 {@link com.baomidou.mybatisplus.core.conditions.query.QueryWrapper}
     * @param mapper       转换函数
     */
    <V> V getObj(Wrapper<T> queryWrapper, Function<? super Object, V> mapper);

    /**
     * 查询总记录数
     *
     * @see Wrappers#emptyWrapper()
     */
    default int count() {
        return count(Wrappers.emptyWrapper());
    }

    /**
     * 根据 Wrapper 条件,查询总记录数
     *
     * @param queryWrapper 实体对象封装操作类 {@link com.baomidou.mybatisplus.core.conditions.query.QueryWrapper}
     */
    default int count(Wrapper<T> queryWrapper) {
        return SqlHelper.retCount(getBaseMapper().selectCount(queryWrapper));
    }

    /**
     * 查询列表
     *
     * @param queryWrapper 实体对象封装操作类 {@link com.baomidou.mybatisplus.core.conditions.query.QueryWrapper}
     */
    default List<T> list(Wrapper<T> queryWrapper) {
        return getBaseMapper().selectList(queryWrapper);
    }

    /**
     * 查询所有
     *
     * @see Wrappers#emptyWrapper()
     */
    default List<T> list() {
        return list(Wrappers.emptyWrapper());
    }

    /**
     * 翻页查询
     *
     * @param page         翻页对象
     * @param queryWrapper 实体对象封装操作类 {@link com.baomidou.mybatisplus.core.conditions.query.QueryWrapper}
     */
    default <E extends IPage<T>> E page(E page, Wrapper<T> queryWrapper) {
        return getBaseMapper().selectPage(page, queryWrapper);
    }

    /**
     * 无条件翻页查询
     *
     * @param page 翻页对象
     * @see Wrappers#emptyWrapper()
     */
    default <E extends IPage<T>> E page(E page) {
        return page(page, Wrappers.emptyWrapper());
    }

    /**
     * 查询列表
     *
     * @param queryWrapper 实体对象封装操作类 {@link com.baomidou.mybatisplus.core.conditions.query.QueryWrapper}
     */
    default List<Map<String, Object>> listMaps(Wrapper<T> queryWrapper) {
        return getBaseMapper().selectMaps(queryWrapper);
    }

    /**
     * 查询所有列表
     *
     * @see Wrappers#emptyWrapper()
     */
    default List<Map<String, Object>> listMaps() {
        return listMaps(Wrappers.emptyWrapper());
    }

    /**
     * 查询全部记录
     */
    default List<Object> listObjs() {
        return listObjs(Function.identity());
    }

    /**
     * 查询全部记录
     *
     * @param mapper 转换函数
     */
    default <V> List<V> listObjs(Function<? super Object, V> mapper) {
        return listObjs(Wrappers.emptyWrapper(), mapper);
    }

    /**
     * 根据 Wrapper 条件,查询全部记录
     *
     * @param queryWrapper 实体对象封装操作类 {@link com.baomidou.mybatisplus.core.conditions.query.QueryWrapper}
     */
    default List<Object> listObjs(Wrapper<T> queryWrapper) {
        return listObjs(queryWrapper, Function.identity());
    }

    /**
     * 根据 Wrapper 条件,查询全部记录
     *
     * @param queryWrapper 实体对象封装操作类 {@link com.baomidou.mybatisplus.core.conditions.query.QueryWrapper}
     * @param mapper       转换函数
     */
    default <V> List<V> listObjs(Wrapper<T> queryWrapper, Function<? super Object, V> mapper) {
        return getBaseMapper().selectObjs(queryWrapper).stream().filter(Objects::nonNull).map(mapper).collect(Collectors.toList());
    }

    /**
     * 翻页查询
     *
     * @param page         翻页对象
     * @param queryWrapper 实体对象封装操作类 {@link com.baomidou.mybatisplus.core.conditions.query.QueryWrapper}
     */
    default <E extends IPage<Map<String, Object>>> E pageMaps(E page, Wrapper<T> queryWrapper) {
        return getBaseMapper().selectMapsPage(page, queryWrapper);
    }

    /**
     * 无条件翻页查询
     *
     * @param page 翻页对象
     * @see Wrappers#emptyWrapper()
     */
    default <E extends IPage<Map<String, Object>>> E pageMaps(E page) {
        return pageMaps(page, Wrappers.emptyWrapper());
    }

    /**
     * 获取对应 entity 的 BaseMapper
     *
     * @return BaseMapper
     */
    BaseMapper<T> getBaseMapper();

    /**
     * 以下的方法使用介绍:
     *
     * 一. 名称介绍
     * 1. 方法名带有 query 的为对数据的查询操作, 方法名带有 update 的为对数据的修改操作
     * 2. 方法名带有 lambda 的为内部方法入参 column 支持函数式的
     *
     * 二. 支持介绍
     * 1. 方法名带有 query 的支持以 {@link ChainQuery} 内部的方法名结尾进行数据查询操作
     * 2. 方法名带有 update 的支持以 {@link ChainUpdate} 内部的方法名为结尾进行数据修改操作
     *
     * 三. 使用示例,只用不带 lambda 的方法各展示一个例子,其他类推
     * 1. 根据条件获取一条数据: `query().eq("column", value).one()`
     * 2. 根据条件删除一条数据: `update().eq("column", value).remove()`
     *
     */

    /**
     * 链式查询 普通
     *
     * @return QueryWrapper 的包装类
     */
    default QueryChainWrapper<T> query() {
        return ChainWrappers.queryChain(getBaseMapper());
    }

    /**
     * 链式查询 lambda 式
     * <p>注意:不支持 Kotlin </p>
     *
     * @return LambdaQueryWrapper 的包装类
     */
    default LambdaQueryChainWrapper<T> lambdaQuery() {
        return ChainWrappers.lambdaQueryChain(getBaseMapper());
    }

    /**
     * 链式更改 普通
     *
     * @return UpdateWrapper 的包装类
     */
    default UpdateChainWrapper<T> update() {
        return ChainWrappers.updateChain(getBaseMapper());
    }

    /**
     * 链式更改 lambda 式
     * <p>注意:不支持 Kotlin </p>
     *
     * @return LambdaUpdateWrapper 的包装类
     */
    default LambdaUpdateChainWrapper<T> lambdaUpdate() {
        return ChainWrappers.lambdaUpdateChain(getBaseMapper());
    }

    /**
     * <p>
     * 根据updateWrapper尝试更新,否继续执行saveOrUpdate(T)方法
     * 此次修改主要是减少了此项业务代码的代码量(存在性验证之后的saveOrUpdate操作)
     * </p>
     *
     * @param entity 实体对象
     */
    default boolean saveOrUpdate(T entity, Wrapper<T> updateWrapper) {
        return update(entity, updateWrapper) || saveOrUpdate(entity);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值