您好,登录后才能下订单哦!
本篇内容主要讲解“MybatisPlus中and()和or()如何使用”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“MybatisPlus中and()和or()如何使用”吧!
简单来说,两个子条件间默认and与连接,若两个之间显式写出or()则or或连接.
当需要简单的将两个条件与连接,则最直接的写法为:
QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>(). eq("attr_id",key). eq("catelog_id",catelogId);
当然也可以显式地写出and()如下,但没必要:
QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>(). eq("attr_id",key); queryWrapper.and(qr -> qr.eq("catelog_id", catelogId));
当需要简单的将两个条件或连接,则最直接的写法为:
QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>(). eq("attr_id",key). or(). eq("catelog_id",catelogId);
当然也可以如下,但不那么直观:
QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>(). eq("attr_id",key); queryWrapper.or(qr -> qr.eq("catelog_id", catelogId));
上面有2个不推荐的做法,是因为sql语句为A or B , A and B这种简单连接.当涉及到诸如 A and ( B or C) and D 这类的复杂有优先级的的连接,直接拼接会导致成为 A and B or C and D.所以这时候需要需要or(Consumer consumer),and(Consumer consumer)这两个方法.示例如下:
QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("attr_type", "base".equalsIgnoreCase(type) ? 1 : 0); queryWrapper.and(qr -> qr.eq("attr_id", key). or(). like("attr_name", key) ); queryWrapper.and(qr -> qr.eq("catelog_id", catelogId));
生成的sql语句如下:
select ... WHERE (attr_type = ? AND ( (attr_id = ? OR attr_name LIKE ?) ) AND ( (catelog_id = ?) )) ...;
由此还可见or(Consumer consumer),and(Consumer consumer)这两个方法参数为Consumer时,会在连接处生成2对括号,以此提高优先级.
案例1:where A=? and B=?
//SELECT id,name,age,sex FROM student WHERE (name = ? AND age = ?) List<Student> list = studentService.lambdaQuery().eq(Student::getName, "1").eq(Student::getAge, 1).list();
案例2:where A=? or B=?
//SELECT id,name,age,sex FROM student WHERE (name = ? OR age = ?) List<Student> list = studentService.lambdaQuery().eq(Student::getName, "1").or().eq(Student::getAge, 12).list();
案例3:where A=? or(C=? and D=?)
//SELECT id,name,age,sex FROM student WHERE (name = ? OR (name = ? AND age = ?)) List<Student> list = studentService .lambdaQuery() .eq(Student::getName, "1") .or(wp -> wp.eq(Student::getName, "1").eq(Student::getAge, 12)) .list();
案例4:where (A=?andB=?)or(C=?andD=?)
// SELECT id,name,age,sex FROM student WHERE ((name = ? AND age = ?) OR (name = ? AND age = ?)) List<Student> list = studentService .lambdaQuery() .and(wp -> wp.eq(Student::getName, "1").eq(Student::getAge, 12)) .or(wp -> wp.eq(Student::getName, "1").eq(Student::getAge, 12)) .list();
案例5:whert A =? or (B=? and ( C=? or D=?))
// SELECT * FROM student WHERE ((name <> 1) OR (name = 1 AND (age IS NULL OR age >= 11))) List<Student> list = studentService .lambdaQuery() .and(wp -> wp.ne(Student::getName, "1")) .or( wp -> wp.eq(Student::getName, "1") .and(wpp -> wpp.isNull(Student::getAge).or().ge(Student::getAge, 11))) .list();
到此,相信大家对“MybatisPlus中and()和or()如何使用”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。