mybatis处理and、or关系的方法

来源:互联网 发布:2017神优化单机游戏 编辑:程序博客网 时间:2024/06/03 16:13

转自  http://blog.csdn.net/wang_song_yan/article/details/49081901

1.( xx and xx) or ( xx and xx) 

实例代码:

[java] view plain copy
  1. BaUserExample baUserExample = new BaUserExample();  
  2.   
  3. Criteria criteria1 = baUserExample.createCriteria();  
  4. criteria1.andOrgIdEqualTo("1");  
  5. criteria1.andDeptIdEqualTo("1");  
  6.               
  7. Criteria criteria2 = baUserExample.createCriteria();  
  8. criteria2.andUserNameEqualTo("name");  
  9. criteria2.andEmailLike("%test@%");  
  10.               
  11. baUserExample.or(criteria2);  
  12.   
  13. userMapper.countByExample(baUserExample);  

执行的sql语句:

[java] view plain copy
  1. ==>  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 <>? )

实例代码:

[java] view plain copy
  1. BaUserExample baUserExample = new BaUserExample();  
  2.   
  3. Criteria criteria1 = baUserExample.createCriteria();  
  4. criteria1.andUserNameLike("%name%");  
  5. criteria1.andDeptIdIsNull();  
  6.               
  7. Criteria criteria2 = baUserExample.createCriteria();  
  8. criteria2.andUserNameLike("%name%");  
  9. criteria2.andDeptIdNotEqualTo("1");  
  10.               
  11. baUserExample.or(criteria2);  
  12.   
  13. userMapper.countByExample(baUserExample);  


执行的sql语句:

[java] view plain copy
  1. ==>  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功能调换(还没尝试过)。
原创粉丝点击