一. 简单无优先级连接(即无括号的sql语句)
简单来说,两个子条件间默认and与连接,若两个之间显式写出or()则or或连接.
1. 与连接 and()
当需要简单的将两个条件与连接,则最直接的写法为:
1
2
3
|
QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().
eq("attr_id",key).
eq("catelog_id",catelogId);
|
当然也可以显式地写出and()如下,但没必要:
1
2
3
4
|
QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().
eq("attr_id",key);
queryWrapper.and(qr -> qr.eq("catelog_id", catelogId));
|
2. 或连接 or()
当需要简单的将两个条件或连接,则最直接的写法为:
1
2
3
4
|
QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().
eq("attr_id",key).
or().
eq("catelog_id",catelogId);
|
当然也可以如下,但不那么直观:
1
2
3
4
|
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)这两个方法.示例如下:
1
2
3
4
5
6
7
|
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语句如下:
1
2
3
|
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=?
1
2
|
//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=?
1
2
|
//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=?)
1
2
3
4
5
6
7
|
//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=?)
1
2
3
4
5
6
7
|
// 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=?))
1
2
3
4
5
6
7
8
9
10
|
// 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();
|
|