Mybatis plus where添加括号
List<String> list = xxxx;
QueryWrapper queryWrapper = new QueryWrapper<>();
queryWrapper.and(wrapper -> {
for(String bm : list) {
wrapper.like("xxxxx", bm).or();
}
return wrapper;
});
queryWrapper.like("xx", "xxx");
打印的效果大概如下:
select * from table_name where (colA like '%xx%' or colA like '%xx%') and colB like '%xx%'
where或and后面的条件用括号括起来
今天在使用mybatisplus时需要将and后面的or条件使用括号包起来
@ApiOperation(value = "查看粉丝列表", notes = "查看粉丝列表")
@PostMapping("/fansList")
public ResultVO<ResultListVO<LitemallBusiness>> fansList(@RequestParam(value = "bid") Integer bid,
@RequestParam(value = "nickName", required = false) String nickName) {
try {
QueryWrapper<LitemallBusiness> queryWrapperw = new QueryWrapper<LitemallBusiness>();
queryWrapperw.eq("pid", bid).or().eq("pid2",bid);
if (nickName != null && !nickName.equals("")) {
queryWrapperw.like("nick_name", nickName);
}
queryWrapperw.eq("deleted", false);
List<LitemallBusiness> litemall_businessList = businessService.list(queryWrapperw);
return ResponseUtil.okList(litemall_businessList);
} catch (Exception e) {
e.printStackTrace();
return ResponseUtil.serious();
}
}
打印输出的sql
select * form litemall_business where deleted=0 and pid=1 or pid2=1
此条sql是没办法满足我需要的数据
实际上的我需要执行的sql是需要把and后面的or用()包起来作为一个条件来查询
所以mybatisplus的原生查询方法需要修改为:
@ApiOperation(value = "查看粉丝列表", notes = "查看粉丝列表")
@PostMapping("/fansList")
public ResultVO<ResultListVO<LitemallBusiness>> fansList(@RequestParam(value = "bid") Integer bid,
@RequestParam(value = "nickName", required = false) String nickName) {
try {
QueryWrapper<LitemallBusiness> queryWrapperw = new QueryWrapper<LitemallBusiness>();
queryWrapperw.and(wrapper -> wrapper.eq("pid", bid).or().eq("pid2", bid));
// queryWrapperw.eq("pid", bid).or().eq("pid2",bid);
if (nickName != null && !nickName.equals("")) {
queryWrapperw.like("nick_name", nickName);
}
queryWrapperw.eq("deleted", false);
List<LitemallBusiness> litemall_businessList = businessService.list(queryWrapperw);
return ResponseUtil.okList(litemall_businessList);
} catch (Exception e) {
e.printStackTrace();
return ResponseUtil.serious();
}
}
这样sql打印出来就是:
select * form litemall_business where deleted=0 and (pid=1 or pid2=1)
这样就满足了我把and后面的or作为一个整体
这里需要注意的是:我的mybatisplus版本是3.0.7.1,这个版本中是没有andNew()的方法,所以需要使用这种方法时查看你的版本是否和我的一样,还有一点要注意,不要丢弃了语句中的.and()
这里顺便补充一下andNew()的写法
//mybatisplus版本3.0.7.1 jdk1.8
queryWrapperw.and(wrapper -> wrapper.eq("pid", bid).or().eq("pid2", bid));
//执行sql
select * form litemall_business where deleted=0 and (pid=1 or pid2=1)
//mybatisplus版本低于3.0.7.1
queryWrapperw.andNew().eq("pid", bid).or().eq("pid2", bid);
//执行sql
select * form litemall_business where deleted=0 and (pid=1 or pid2=1)
其实最终执行的sql是一样的
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。