我是靠谱客的博主 单薄发箍,这篇文章主要介绍MyBatis Example And与Or混合使用的实例,现在分享给大家,希望可以做个参考。

MyBatis Example And与Or混合使用

(条件1 and 条件2) or ( 条件3 and 条件4)

复制代码
1
2
3
4
5
6
7
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 )

复制代码
1
2
3
4
5
6
7
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关系方法

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

实例代码:

复制代码
1
2
3
4
5
6
7
8
9
10
11
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语句:

复制代码
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 )

所以就转变成第一种方法

举个例子,假如想要实现

复制代码
1
select count(*) from ba_user WHERE userName like ? and ( dept_id is null or dept_id <>? )

可以转化为

复制代码
1
select count(*) from ba_user WHERE (userName like ? and dept_id is null ) or ( userName like ? and dept_id <>? )

实例代码:

复制代码
1
2
3
4
5
6
7
8
9
10
11
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语句:

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

以上为个人经验,希望能给大家一个参考,也希望大家多多支持靠谱客。

最后

以上就是单薄发箍最近收集整理的关于MyBatis Example And与Or混合使用的实例的全部内容,更多相关MyBatis Example And与Or混合使用内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(135)

评论列表共有 0 条评论

立即
投稿
返回
顶部