mybatis -plus基本查询

Posted 在那里遇见你

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mybatis -plus基本查询相关的知识,希望对你有一定的参考价值。

2.查询

一、基本查询


普通查询:使用方式为实现BaseMapper接口对象调用该方法。

  1. T selectById(Serializable id):使用场景为通过主键查询,只要该主键类型实现了Serialzable接口即可。

2、List selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList):使用场景为通过主键的集合去批量查询,前提主键的类型实现了Serializable接口。传入array

3、List selectByMap(@Param(Constants.COLUMN_MAP) Map<String,Object> columnMap):使用场景为传入一个Map集合,key为表字段,value为表字段值。注意:Map的key为数据表的字段名,不是实体类属性名

and查询的时候,put进去的key是数据库中的列名,不是实体类的属性名


public class RetrieveTest 

    @Autowired
    private UserMapper userMapper;

    @Test
    public void selectById() 
        User user = userMapper.selectById(1088250446457389058L);
        System.out.println(user);
    

    @Test
    public void selectBatchIds() 
        List<Long> list = Arrays.asList(1088248166370832385L, 1094590409767661570L, 1209509417456001025L);
        List<User> userList = userMapper.selectBatchIds(list);
        userList.forEach(System.out::println);
    

    @Test
    public void selectByMap() 
        Map<String, Object> columnMap = new HashMap<>();
        columnMap.put("name", "李艺伟");
        columnMap.put("age", 28);
        List<User> userList = userMapper.selectByMap(columnMap);
        userList.forEach(System.out::println);
    


二、 BaseMapper以条件构造器(Wrapper)为参数的查询方法

查询构造器 ,通过一个对象来来封装查询条件,查询构造器就是构造查询条件。

AbstractWrapper抽象类:提供了很多条件构造器

List selectList(@Param(Constans.WRAPPER) Wrapper queryWrapper)

  1. 使用场景:对于一些有特殊条件的查询,比如模糊查询、条件查询等。
  2. 使用方法:QueryWrapper为查询条件构造器,它是AbstractWrapper的一个子类。

生成条件构造器

方式一、QueryWrapper<T> queryWrapper=new QueryWrapper<T>();
方式二、QueryWrapper<T> query=Wrappers.<T>query();

注意:条件构造器AbstractWrapper的条件构造器方法key都为数据表字段,value为实际值。
例如:like(Column,value)、gt(Column,value)等

例子:

2.1 查询

一、查询需求

1、名字中包含雨并且年龄小于40

       name like '%雨%' and age<40

2、名字中包含雨年并且龄大于等于20且小于等于40并且email不为空

   name like '%雨%' and age between 20 and 40 and email is not null

3、名字为王姓或者年龄大于等于25,按照年龄降序排列,年龄相同按照id升序排列

   name like '王%' or age>=25 order by age desc,id asc

4、创建日期为2019214日并且直属上级为名字为王姓

      date_format(create_time,'%Y-%m-%d')='2019-02-14' and manager_id in (select id from user where name like '王%')

5、名字为王姓并且(年龄小于40或邮箱不为空)

    name like '王%' and (age<40 or email is not null)

6、名字为王姓或者(年龄小于40并且年龄大于20并且邮箱不为空)

    name like '王%' or (age<40 and age>20 and email is not null)

7、(年龄小于40或邮箱不为空)并且名字为王姓

    (age<40 or email is not null) and name like '王%'

8、年龄为30313435

    age in (30313435) 

9、只返回满足条件的其中一条语句即可

limit 1

二、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

三、统计查询:

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
/**
     * 1、名字中包含雨并且年龄小于40
     *     name like '%雨%' and age<40
     */
    @Test
    public void selectByWrapper() 
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("name", "雨").lt("age", 40);

        List<User> userList = userMapper.selectList(queryWrapper);
        userList.forEach(System.out::println);
    
    /**
     * 2、名字中包含雨年并且龄大于等于20且小于等于40并且email不为空
     *    name like '%雨%' and age between 20 and 40 and email is not null
     */
    @Test
    public void selectByWrapper2() 
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("name", "雨").between("age" ,20 ,40).isNotNull("email");

        List<User> userList = userMapper.selectList(queryWrapper);
        userList.forEach(System.out::println);
    

    /**
     * 3、名字为王姓或者年龄大于等于25,按照年龄降序排列,年龄相同按照id升序排列
     *    name like '王%' or age>=25 order by age desc,id asc
     */
    @Test
    public void selectByWrapper3() 
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.likeRight("name", "王").or().gt("age", 25).orderByDesc("age").orderByAsc("id");

        List<User> userList = userMapper.selectList(queryWrapper);
        userList.forEach(System.out::println);
    

  

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 ‘王%’)

apply(sql,prams)
inSql("字段",sql子查询)



QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
queryWrapper.apply("date_format(create_time,'%Y-%m-%d') = 0","2019-02-14").inSql("manager_id","select id from user where name like '王%' ");
List<User> userList = userMapper.selectList(queryWrapper);
userList.forEach(System.out::println);

// 此处写法存在sql注入问题,不建议使用
userQuery.apply("date_format(create_time,'%Y-%m-%d')='2019-02-14' or true or true").inSql("manager_id","select id from user where name like '王%'");

queryWrapper.apply("phone","888888").inSql("username","select username from user where id = 3");

date_format(日期,'格式'):将日期按照格式进行插入或者返回。例如:date_format(now(),'%Y-%m-%d')。
动态条件构造器:apply。范围条件构造器:insql。
注意:如果0替换为实际值,可能会造成sql注入。

public class SelectTest 
    @Autowired
    UserMapper userMapper;

    @Test
    public void selectById() 
        User user = userMapper.selectById(1087982257332887553L);
        System.out.println(user);
    

    @Test
    public void selectBatchIds() 
        List<Long> ids = Arrays.asList(
            1087982257332887553L,
            1094590409767661570L,
            1094592041087729666L
        );
        List<User> list = userMapper.selectBatchIds(ids);
        list.forEach(System.out::println);
    

    @Test
    public void selectByMap() 
        Map<String, Object> map = new HashMap<>();
        //map的key指代的是mysql表中的列名,并非java实体的属性名
        map.put("name", "张雨琪");
        map.put("manager_id", 1088248166370832385L);
        List<User> list = userMapper.selectByMap(map);
        list.forEach(System.out::println);
    

    @Test
    public void selectList_all() 
        List<User> list = userMapper.selectList(null);
        list.forEach(System.out::println);
    

    /**
     * 名字中包含雨,并且年龄小于40
     * SELECT * FROM `user`
     * WHERE `name` LIKE '%雨%' AND `age`< 40
     */
    @Test
    public void selectList_like_lt() 
//        QueryWrapper<User> query = Wrappers.<User>query();
        QueryWrapper<User> query = new QueryWrapper<>();
        query.like("name", "雨").lt("age", 40);
        List<User> list = userMapper.selectList(query);
        list.forEach(System.out::println);
    

    /**
     * 名字中包含雨,并且年龄大于等于20且小于等于40,并且email不为空
     * SELECT * FROM `user`
     * WHERE `name` LIKE '%雨%' AND `age` <= 40 AND `age` >= 20 AND `email` IS NOT NULL
     */
    @Test
    public void selectList_between_isNotNull() 
        QueryWrapper<User> query = new QueryWrapper<>();
        query.like("name", "雨").between("age", 20, 40).isNotNull("email");
        List<User> list = userMapper.selectList(query);
        list.forEach(System.out::println);
    

    /**
     * 姓赵或者年龄大于等于25,按照年龄降序排列,年龄相同则按照id升序排列
     * SELECT * FROM `user`
     * WHERE `name` LIKE '赵%' OR `age` >= 25 ORDER BY `age` DESC , `id` ASC;
     */
    @Test
    public void selectList_or_orderByDesc_orderByAsc() 
        QueryWrapper<User> query = new QueryWrapper<>();
        query.likeRight("name", "赵").or().ge("age", 20)
            .orderByDesc("age").orderByAsc("id");
        List<User> list = userMapper.selectList(query);
        list.forEach(System.out::println);
    

    /**
     * 创建日期为2019年2月14日,且直属上级姓王
     * SELECT * FROM `user`
     * WHERE DATE_FORMAT(create_time,'%Y-%m-%d')='2019-02-14'
     * AND manager_id IN (SELECT id FROM `user` WHERE `name` LIKE '王%')
     */
    @Test
    public void selectList_apply_inSql() 
        QueryWrapper<User> query = new QueryWrapper<>();
        query.apply("DATE_FORMAT(create_time,'%Y-%m-%d')=0", "2019-02-14")
            .inSql("manager_id", "SELECT id FROM `user` WHERE `name` LIKE '王%'");
        List<User> list = userMapper.selectList(query);
        list.forEach(System.out::println);
    

    /**
     * 姓王且(年龄小于40或邮箱不为空)
     * SELECT * FROM `user`
     * WHERE `name` LIKE '王%' AND (`age`< 40 OR `email` IS NOT NULL)
     */
    @Test
    public void selectList_and_lambda() 
        QueryWrapper<User> query = new QueryWrapper<>();
        query.likeRight("name", "王")
            .and(q -> q.lt("age", 40).or().isNotNull("email"));
        List<User> list = userMapper.selectList(query);
        list.forEach(System.out::println);
    

    /**
     * 姓王且或者(年龄小于40且年龄大于20且邮箱不为空)
     * SELECT * FROM `user`
     * WHERE `name` LIKE '王%' OR (`age`< 40 AND `age` > 20  AND `email` IS NOT NULL)
     */
    @Test
    public void selectList_or_lambda() 
        QueryWrapper<User> query = new QueryWrapper<>();
        query.likeRight("name", "王")
            .or(q -> q.lt("age", 40).gt("age", 20).isNotNull("email"));
        List<User> list = userMapper.selectList(query);
        list.forEach(System.out::println);
    

    /**
     * (年龄小于40或邮箱不为空)且姓王
     * SELECT * FROM `user`
     * WHERE (`age`< 40 OR `email` IS NOT NULL) AND `name` LIKE '王%'
     */
    @Test
    public void selectList_nested() 
        QueryWrapper<User> query = new QueryWrapper<>();
        query.nested(q -> q.lt("age", 40).or().isNotNull("email"))
            .likeRight("name", "王");
        List<User> list = userMapper.selectList(query);
        list.forEach(System.out::println);
    

    /**
     * 年龄为30,31,34,35
     * SELECT * FROM `user` WHERE `age` IN (30,31,34,35);
     */
    @Test
    public void selectList_in() 
        QueryWrapper<User> query = new QueryWrapper<>();
        query.in("age", Arrays.asList(30, 31, 34, 35));
        List<User> list = userMapper.selectList(query);
        list.forEach(System.out::println);
    

    /**
     * 返回只满足条件的一条(只调用最后一次,有sql注入的风险)
     * SELECT * FROM `user` WHERE `age` IN (30,31,34,35) LIMIT 1;
     */
    @Test
    public void selectList_last() 
        QueryWrapper<User> query = new QueryWrapper<>();
        query.in("age", Arrays.asList(30, 31, 34, 35)).last("limit 1");
        List<User> list = userMapper.selectList(query);
        list.forEach(System.out::println);
    

    /**
     * 只查询指定字段
     * SELECT `name`,`age` FROM `user` WHERE `age` IN (30,31,34,35) LIMIT 1;
     */
    @Test
    public void selectList_select_include() 
        QueryWrapper<User> query = new QueryWrapper<>();
        query.select("name", "age").in("age", Arrays.asList(30, 31, 34, 35)).last("limit 1");
        List<User> list = userMapper.selectList(query);
        list.forEach(System.out::println);
    

    /**
     * 排除指定字段
     */
    @Test
    public void selectList_select_exclude() 
        QueryWrapper<User> query = new QueryWrapper<>();
        query.in("age", Arrays.asList(30, 31, 34, 35)).last("limit 1")
            .select(
                User.class,
                info -> !info.getColumn().equals("create_time") && !info.getColumn()

(c)2006-2024 SYSTEM All Rights Reserved IT常识