1.( xx and xx) or ( xx and xx)
實例代碼:
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);
執行的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)
暫時沒找到直接的sql語句構造方法,但是經過轉換還是可以實現的
根據邏輯表達式可以知道 a and ( b or c ) = ( a and b) or ( a and c )
所以就轉變成第一種方法
舉個例子,假如想要實現 select count(*) from ba_user WHERE userName like ? and ( dept_id is null or dept_id <>? )
可以轉化爲select count(*) from ba_user WHERE (userName like ? and dept_id is null ) or ( userName like ? and dept_id <>? )
實例代碼:
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);
執行的sql語句:
==> Preparing: select count(*) from ba_user WHERE ( user_name like ? and dept_id is null ) or( user_name like ? and dept_id <> ? )
這算是一種取巧的方法吧,對於這樣的問題可以自己編寫mapper.xml文件,或者在代碼裏面過濾,還有一種思路就是修改Criteria的代碼實現and和or功能調換(還沒嘗試過)。