Mybatis-Plus中and()和or()的使用与原理详解

88 阅读1分钟

案例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 = tudentService.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();