一. 简单无优先级连接(即无括号的sql语句)
简单来说,两个子条件间默认and与连接,若两个之间显式写出or()则or或连接.
1. 与连接 and()
当需要简单的将两个条件与连接,则最直接的写法为:
QueryWrapperqueryWrapper = new QueryWrapper (). eq("attr_id",key). eq("catelog_id",catelogId);
当然也可以显式地写出and()如下,但没必要:
QueryWrapperqueryWrapper = new QueryWrapper (). eq("attr_id",key); queryWrapper.and(qr -> qr.eq("catelog_id", catelogId));
2. 或连接 or()
当需要简单的将两个条件或连接,则最直接的写法为:
QueryWrapperqueryWrapper = new QueryWrapper (). eq("attr_id",key). or(). eq("catelog_id",catelogId);
当然也可以如下,但不那么直观:
QueryWrapperqueryWrapper = new QueryWrapper (). 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)这两个方法.示例如下:
QueryWrapperqueryWrapper = new QueryWrapper ().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对括号,以此提高优先级.
补充:MybatisPlus中and和or的组合使用
案例1:where A=? and B=?
//SELECT id,name,age,sex FROM student WHERE (name = ? AND age = ?) Listlist = 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 = ?) Listlist = 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 = ?)) Listlist = 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 = ?)) Listlist = 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))) Listlist = 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();
总结
到此这篇关于Mybatis-Plus中and()和or()使用与原理的文章就介绍到这了,更多相关Mybatis-Plus中and()和or()使用内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!