MyBatis Example And與Or混合使用的實(shí)例
MyBatis Example And與Or混合使用
(條件1 and 條件2) or ( 條件3 and 條件4)
MemberExample example = new MemberExample();
MemberExample.Criteria c1 = example.createCriteria();
c1.andOne(A).andTwo(B);
MemberExample.Criteria c2 = example.createCriteria();
c2.andThree(C).andFour(D);
example.or(c2);
條件1 and (條件2 or 條件3)
思路 : 分拆 : A and ( B or C ) ==> ( A and B ) or ( A and C )
MemberExample example = new MemberExample();
MemberExample.Criteria c1 = example.createCriteria();
c1.andOne(A).andTwo(B);
MemberExample.Criteria c2 = example.createCriteria();
c2.andOne(A).andThree(C);
example.or(c2);
MyBatis Example 處理And、Or關(guān)系方法
1.( xx and xx) or ( xx and xx)
實(shí)例代碼:
BaUserExample baUserExample = new BaUserExample();
Criteria criteria1 = baUserExample.createCriteria();
criteria1.andOrgIdEqualTo("1");
criteria1.andDeptIdEqualTo("1");
Criteria criteria2 = baUserExample.createCriteria();
criteria2.andUserNameEqualTo("name");
criteria2.andEmailLike("%test@%");
baUserExample.or(criteria2);
userMapper.countByExample(baUserExample);
執(zhí)行的sql語句:
==> Preparing: select count(*) from ba_user WHERE ( org_id = ? and dept_id = ? ) or( user_name = ? and email like ? )
2.xx and ( xx or xx)
暫時(shí)沒找到直接的sql語句構(gòu)造方法,但是經(jīng)過轉(zhuǎn)換還是可以實(shí)現(xiàn)的
根據(jù)邏輯表達(dá)式可以知道 a and ( b or c ) = ( a and b) or ( a and c )
所以就轉(zhuǎn)變成第一種方法
舉個(gè)例子,假如想要實(shí)現(xiàn)
select count(*) from ba_user WHERE userName like ? and ( dept_id is null or dept_id <>? )
可以轉(zhuǎn)化為
select count(*) from ba_user WHERE (userName like ? and dept_id is null ) or ( userName like ? and dept_id <>? )
實(shí)例代碼:
BaUserExample baUserExample = new BaUserExample();
Criteria criteria1 = baUserExample.createCriteria();
criteria1.andUserNameLike("%name%");
criteria1.andDeptIdIsNull();
Criteria criteria2 = baUserExample.createCriteria();
criteria2.andUserNameLike("%name%");
criteria2.andDeptIdNotEqualTo("1");
baUserExample.or(criteria2);
userMapper.countByExample(baUserExample);
執(zhí)行的sql語句:
==> Preparing: select count(*) from ba_user WHERE ( user_name like ? and dept_id is null ) or( user_name like ? and dept_id <> ? )
這算是一種取巧的方法吧,對(duì)于這樣的問題可以自己編寫mapper.xml文件,或者在代碼里面過濾,還有一種思路就是修改Criteria的代碼實(shí)現(xiàn)and和or功能調(diào)換(還沒嘗試過)。
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
spring?@value無法取值多個(gè)properties文件的解決
這篇文章主要介紹了spring?@value無法取值多個(gè)properties文件的解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-03-03
基于Jenkins搭建.NET Core持續(xù)集成環(huán)境過程圖解
這篇文章主要介紹了基于Jenkins搭建.NET Core持續(xù)集成環(huán)境過程圖解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-08-08
mybatis連接mysql的實(shí)現(xiàn)過程
通過配置Maven的pom文件,可以簡(jiǎn)化MyBatis連接數(shù)據(jù)庫的過程,免去手動(dòng)下載和導(dǎo)入各種依賴包的麻煩,本文介紹了如何利用Maven導(dǎo)入MyBatis及其他相關(guān)依賴,如Junit、MySQL連接驅(qū)動(dòng)、Druid連接池和Dbutil等,以簡(jiǎn)化數(shù)據(jù)庫操作和測(cè)試2024-10-10

