3.MybatisPlus 查询方法

1.普通查询

package com.mp;
import com.mp.dao.UserMapper;
import com.mp.entity.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * @Description 测试类,测试普通查询方法
 * @Author LL
 * @Date 2020-03-22 12:35
 */
@SpringBootTest
@RunWith(SpringRunner.class)
public class RetrieveTest {

    @Autowired
    private UserMapper userMapper;

    //根据id查询
    @Test
    public void selectById(){
        User user = userMapper.selectById(1094590409767661570L);
        System.out.println(user);
    }

    //根据多个id查询
    @Test
    public void selectByIds(){
        List ids = Arrays.asList(1094590409767661570L, 1094592041087729666L, 
                1241614720021913602L);
        List users = userMapper.selectBatchIds(ids);
        users.forEach(System.out::println);
    }

    //根据条件map参数查询
    @Test
    public void selectByMap(){
        //map中的key值为数据库表中的字段,值为查询条件值
        HashMap paramMap = new HashMap<>();
        paramMap.put("name", "王天风");
        paramMap.put("age", 25);
        List users = userMapper.selectByMap(paramMap);
        users.forEach(System.out::println);
    }
}

2.条件构造器查询

package com.mp;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.mp.dao.UserMapper;
import com.mp.entity.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

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

/**
 * @Description 测试类,测试条件构造器查询方法
 * @Author LL
 * @Date 2020-03-22 12:35
 */
@SpringBootTest
@RunWith(SpringRunner.class)
public class RetrieveWrapperTest {

    @Autowired
    private UserMapper userMapper;

    /**
     * 名字中包含雨并且年龄小于40
     * name like '%雨%' and age<40
     */
    @Test
    public void selectByWrapper(){
        QueryWrapper queryWrapper = new QueryWrapper<>();
//        QueryWrapper query = Wrappers.query();
        queryWrapper.like("name", "雨")
                .lt("age", 40);
        List users = userMapper.selectList(queryWrapper);
        users.forEach(System.out::println);
    }

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

    /**
     * 名字为王姓或者年龄大于等于25,按照年龄降序排列,年龄相同按照id升序排列
     *  name like '王%' or age>=25 order by age desc,id asc
     */
    @Test
    public void selectByWrapper3(){
        QueryWrapper query = Wrappers.query();
        query.like("name", "王")
                .or()
                .ge("age", 25)
                .orderByDesc("age")
                .orderByAsc("id");
        List users = userMapper.selectList(query);
        users.forEach(System.out::println);
    }

    /**
     * 创建日期为2019年2月14日并且直属上级为名字为王姓
     * date_format(create_time,'%Y-%m-%d')='2019-02-14'
     * and manager_id in (select id from user where name like '王%')
     */
    @Test
    public void selectByWrapper4(){
        QueryWrapper query = Wrappers.query();
        String date = "2019-02-14";
        String name = "王";
        query.apply("date_format(create_time,'%Y-%m-%d')={0}", date)
                .inSql("manager_id", "select id from user where name like '"+name+"%'");
        List users = userMapper.selectList(query);
        users.forEach(System.out::println);
    }

    /**
     * 名字为王姓并且(年龄小于40或邮箱不为空)
     * name like '王%' and (age<40 or email is not null)
     */
    @Test
    public void selectByWrapper5(){
        QueryWrapper query = Wrappers.query();
        query.likeRight("name", "王")
                .and(wq->wq.lt("age", 40)
                        .or()
                        .isNotNull("email")
                );
        List users = userMapper.selectList(query);
        users.forEach(System.out::println);
    }

    /**
     * 名字为王姓或者(年龄小于40并且年龄大于20并且邮箱不为空)
     * name like '王%' or (age<40 and age>20 and email is not null)
     */
    @Test
    public void selectByWrapper6(){
        QueryWrapper query = Wrappers.query();
        query.likeRight("name", "王")
                .or(wq->wq.lt("age", 40)
                        .gt("age", 20)
                        .isNotNull("email")
                );
        List users = userMapper.selectList(query);
        users.forEach(System.out::println);
    }

    /**
     * (年龄小于40或邮箱不为空)并且名字为王姓
     * (age<40 or email is not null) and name like '王%'
     */
    @Test
    public void selectByWrapper7(){
        QueryWrapper query = Wrappers.query();
        query.nested(wq->wq.lt("age", 40).or().isNotNull("email"))
                .likeRight("name", "王");
        List users = userMapper.selectList(query);
        users.forEach(System.out::println);
    }

    /**
     * 年龄为30、31、34、35
     * age in (30、31、34、35)
     */
    @Test
    public void selectByWrapper8(){
        QueryWrapper query = Wrappers.query();
        query.in("age", Arrays.asList(30,31,34,35));
        List users = userMapper.selectList(query);
        users.forEach(System.out::println);
    }

    /**
     * 只返回满足条件的其中一条语句即可
     * limit 1
     */
    @Test
    public void selectByWrapper9(){
        QueryWrapper query = Wrappers.query();
        query.in("age", Arrays.asList(30,31,34,35)).last("limit 1");
        List users = userMapper.selectList(query);
        users.forEach(System.out::println);
    }
}

3.在select中字段不全部出现的查询

package com.mp;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mp.dao.UserMapper;
import com.mp.entity.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;

/**
 * @Description 测试类,select中字段不全部出现的查询
 * @Author LL
 * @Date 2020-03-22 12:35
 */
@SpringBootTest
@RunWith(SpringRunner.class)
public class RetrieveWrapperTest2 {

    @Autowired
    private UserMapper userMapper;

    /**
     * 名字中包含雨并且年龄小于40
     * 第一种情况:select id,name
     *             from user
     *             where name like '%雨%' and age<40
     */
    @Test
    public void selectByWrapper10(){
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id", "name")
                .like("name", "雨")
                .lt("age", 40);
        List users = userMapper.selectList(queryWrapper);
        users.forEach(System.out::println);
    }

    /**
     * 名字中包含雨并且年龄小于40
     * 第二种情况:select id,name,age,email
     *             from user
     *             where name like '%雨%' and age<40
     */
    @Test
    public void selectByWrapper11(){
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.like("name", "雨")
                .lt("age", 40)
                .select(User.class, info->!info.getColumn().equals("create_time")
                &&!info.getColumn().equals("manager_id"));
        List users = userMapper.selectList(queryWrapper);
        users.forEach(System.out::println);
    }
}

4.condition的使用

在添加sql条件时,会判断条件是否存在从而动态拼接sql

package com.mp;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.mp.dao.UserMapper;
import com.mp.entity.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;

/**
 * @Description 测试类,condition的使用
 * @Author LL
 * @Date 2020-03-22 18:35
 */
@SpringBootTest
@RunWith(SpringRunner.class)
public class ConditionTest {

    @Autowired
    private UserMapper userMapper;

    //根据条件拼接SQL
    private void conditionWrapper(String name, String email){
        QueryWrapper query = Wrappers.query();
//        if (StringUtils.isNotEmpty(name)){
//            query.like("name", name);
//        }
//        if (StringUtils.isNotEmpty(email)){
//            query.like("email", email);
//        }

        //根据condition的条件判断是否拼接对应的查询条件
        query.like(StringUtils.isNotEmpty(name), "name", name)
                .like(StringUtils.isNotEmpty(email), "email", email);
        List users = userMapper.selectList(query);
        users.forEach(System.out::println);
    }

    @Test
    public void test(){
        String name = "王";
        String email = "";
        conditionWrapper(name, email);
    }

}

5.实体对象作为条件构造器构造方法的参数

package com.mp;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.mp.dao.UserMapper;
import com.mp.entity.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;

/**
 * @Description 测试类,condition的使用
 * @Author LL
 * @Date 2020-03-22 18:35
 */
@SpringBootTest
@RunWith(SpringRunner.class)
public class ConditionTest {

    @Autowired
    private UserMapper userMapper;

    /**
     * 测试实体类作为条件参数
     */
    @Test
    public void testEntity(){
        User user = new User()
                .setName("张三").setAge(31);

        QueryWrapper query = Wrappers.query(user);
        List users = userMapper.selectList(query);
        users.forEach(System.out::println);
    }
}

如果名称需要模糊查询,可以在User实体类的相应字段上添加注解,注解参数可查看SqlCondition.java

package com.mp.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.experimental.Accessors;

import java.time.LocalDateTime;

/**
 * @Description 实体类
 * @Author LL
 * @Date 2020-03-22 12:22
 */
@Data
@Accessors(chain = true)
@TableName("user")//指定表名称
public class User {

    @TableId//指明此字段为主键id
    private Long id;//主键

    @TableField(condition = SqlCondition.LIKE)//指定查询时的查询形式,name like '%?%'
    private String name;//姓名

    @TableField(condition = "%s<#{%s}")//指定查询时的查询形式,age

查询SQL:SELECT id,create_time,name,manager_id,email,age FROM user WHERE name LIKE CONCAT('%',?,'%') AND age

6.AllEq的用法

package com.mp;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.mp.dao.UserMapper;
import com.mp.entity.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description 测试类,AllEq的使用
 * @Author LL
 * @Date 2020-03-22 18:35
 */
@SpringBootTest
@RunWith(SpringRunner.class)
public class AllEqTest {

    @Autowired
    private UserMapper userMapper;

    /**
     * AllEq
     */
    @Test
    public void testAllEq(){
        Map map = new HashMap<>();
        map.put("name", "王天风");
        map.put("age", 25);
//        map.put("age", null);//传null值,则会在Sql中拼接为 is null
        QueryWrapper query = Wrappers.query();
        query.allEq(map);
//        query.allEq((k, v)->k.equals("name"), map);//过滤掉name字段
        List users = userMapper.selectList(query);
        users.forEach(System.out::println);
    }

}

7.其它条件构造器用法

package com.mp;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.mp.dao.UserMapper;
import com.mp.entity.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;
import java.util.Map;

/**
 * @Description 测试类,其它的用法
 * @Author LL
 * @Date 2020-03-22 18:35
 */
@SpringBootTest
@RunWith(SpringRunner.class)
public class OthersTest {

    @Autowired
    private UserMapper userMapper;

    /**
     * 返回值为map类型
     * 在返回结果中不同于实体类不需要的字段值为null时不显示
     */
    @Test
    public void testMap(){
        QueryWrapper query = Wrappers.query();
        query.like("name", "雨").gt("age", 20);
        List> maps = userMapper.selectMaps(query);
        maps.forEach(System.out::println);
    }

    /**
     * 返回结果为Map类型,使用场景如下
     *
     * 按照直属上级分组,查询每组的平均年龄、最大年龄、最小年龄。
     * 并且只取年龄总和小于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 testMap2(){
        QueryWrapper query = Wrappers.query();
        query.select("avg(age) avg_age","min(age) min_age","max(age) max_age")
                .groupBy("manager_id")
                .having("sum(age)<{0}", 500);

        List> maps = userMapper.selectMaps(query);
        maps.forEach(System.out::println);
    }
/*
    查询结果日志:
    DEBUG==>  Preparing: SELECT avg(age) avg_age,min(age) min_age,max(age) max_age FROM user
    GROUP BY manager_id HAVING sum(age) Parameters: 500(Integer)
    TRACE<==    Columns: avg_age, min_age, max_age
    TRACE<==        Row: 40.0000, 40, 40
    TRACE<==        Row: 25.0000, 25, 25
    TRACE<==        Row: 30.5000, 28, 32
    DEBUG<==      Total: 3
    {max_age=40, avg_age=40.0000, min_age=40}
    {max_age=25, avg_age=25.0000, min_age=25}
    {max_age=32, avg_age=30.5000, min_age=28}
*/


    /**
     * 查询总记录数
     */
    @Test
    public void testCount(){
        QueryWrapper query = Wrappers.query();
        query.like("name", "雨").gt("age", 20);
        int count = userMapper.selectCount(query);
        System.out.println("总记录数:"+count);
    }
/*
    查询结果日志:
    DEBUG==>  Preparing: SELECT COUNT( 1 ) FROM user WHERE (name LIKE ? AND age > ?)
    DEBUG==> Parameters: %雨%(String), 20(Integer)
    TRACE<==    Columns: COUNT( 1 )
    TRACE<==        Row: 2
    DEBUG<==      Total: 1
    总记录数:2
 */


    /**
     * 查询结果为一条数据,多条会报错
     */
    @Test
    public void testOne(){
        QueryWrapper query = Wrappers.query();
        query.like("name", "雨").gt("age", 31);
        User user = userMapper.selectOne(query);
        System.out.println(user);
    }

}

8.lambda条件构造器用法

package com.mp;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.additional.query.impl.LambdaQueryChainWrapper;
import com.mp.dao.UserMapper;
import com.mp.entity.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;

/**
 * @Description 测试类,Lambda条件构造器用法
 * @Author LL
 * @Date 2020-03-22 19:35
 */
@SpringBootTest
@RunWith(SpringRunner.class)
public class LambdaTest {

    @Autowired
    private UserMapper userMapper;

    /**
     * lambda条件构造器
     */
    @Test
    public void selectLambda(){
        //Lamdba条件构造器创建方式
//        LambdaQueryWrapper lambda = new QueryWrapper().lambda();//方式一
//        LambdaQueryWrapper lambdaWrapper = new LambdaQueryWrapper<>();//方式二
        LambdaQueryWrapper lambdaQuery = Wrappers.lambdaQuery();//方式三
        lambdaQuery.like(User::getName, "雨")
                .lt(User::getAge, 40);
        List users = userMapper.selectList(lambdaQuery);
        users.forEach(System.out::println);
    }

    /**
     * (年龄小于40或邮箱不为空)并且名字为王姓
     * (age<40 or email is not null) and name like '王%'
     */
    @Test
    public void selectLambda2(){
        LambdaQueryWrapper lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.nested(wq->wq.lt(User::getAge, 40).or().isNotNull(User::getEmail))
                .likeRight(User::getName, "王");
        List users = userMapper.selectList(lambdaQuery);
        users.forEach(System.out::println);
    }

    /**
     * 直接使用userMapper接口创建
     */
    @Test
    public void selectLambda3(){
        List users = new LambdaQueryChainWrapper<>(userMapper)
                .like(User::getName, "雨").ge(User::getAge, 20).list();
        users.forEach(System.out::println);
    }
}

你可能感兴趣的:(3.MybatisPlus 查询方法)