java or关系_mybatis example处理and、or关系的方法

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功能调换(还没尝试过)。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值