您的当前位置:首页正文

MyBatis-Plus之条件查询

2024-11-06 来源:个人技术集锦

1.MyBatis-Plus条件查询的三种方式

(1)QueryWrapper条件构造器

		QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("number",555555);
        List<User> users = userMapper.selectList(qw);

(2)Lambda格式QueryWrapper条件构造器(推荐)

		QueryWrapper<User> qw = new QueryWrapper<>();
        qw.lambda().eq(User::getNumber,555555);
        List<User> users = userMapper.selectList(qw);

(3)LambdaQueryWrapper条件构造器(推荐)

	    LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getNumber,555555);
        List<User> users = userMapper.selectList(qw);

2.条件查询

(1)AND条件查询
使用链式编程的方式

		QueryWrapper<User> qw = new QueryWrapper<>();
        qw.lambda().lt(User::getNumber,555555).gt(User::getNumber,111111);

(2)OR条件查询
使用or()方法

		QueryWrapper<User> qw = new QueryWrapper<>();
        qw.lambda().lt(User::getNumber,111111).or().gt(User::getNumber,555555);

(3)范围查询

	    QueryWrapper<User> qw = new QueryWrapper<>();
        qw.lt("number",555555);// 小于
        qw.gt("number",555555);// 大于
        qw.eq("number",555555);// 等于
        qw.le("number",555555);// 小于等于
        qw.ge("number",555555);// 大于等于
        qw.between("number",111111,555555);// 范围
        List<User> users = userMapper.selectList(qw);

(4)模糊匹配

		QueryWrapper<User> qw = new QueryWrapper<>();
        qw.like("name","liu");// %liu%
        qw.likeRight("name","liu");// liu%
        qw.likeLeft("name","liu");// %liu
        List<User> users = userMapper.selectList(qw);

3.null值处理

		User user = new User();
        user.setNumber("111111");
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.lambda().eq(null != user.getNumber(),User::getNumber,user.getNumber());

4.查询投影

(1)字段选择

		// QueryWrapper条件构造器
		QueryWrapper<User> qw = new QueryWrapper<>();
        qw.select("name","number");
        List<User> users = userMapper.selectList(qw);
        // LambdaQueryWrapper条件构造器
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.select(User::getName,User::getNumber);
        List<User> users = userMapper.selectList(lqw);

(2)函数字段
注:LambdaQueryWrapper条件构造器不支持函数字段的投影

 		QueryWrapper<User> qw = new QueryWrapper<>();
        qw.select("count(id) AS id_count","count(name) AS name_count");
        List<Map<String, Object>> users = userMapper.selectMaps(qw);
Top