您好,登錄后才能下訂單哦!
本篇內容主要講解“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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。