mybatis and,or复合查询操作

这篇文章主要介绍了mybatis and,or复合查询操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

要查询的sql:

select * from user where name = ? and (age=? or city=?);

方法1:不使用Example查询

直接在usermapper.xml中修改sql

方法2:使用Example查询

sql可转换成

select * from user where (name = ? and age=?) or (name=? and city=?);

然后使用Example查询

 UserExample example=new UserExample(); example.or().orAgeLike("%"+searchParam+"%").andNameEqualTo(userName); example.or().orCityLike("%"+searchParam+"%").andNameEqualTo(userName);

补充知识:MySQL/Mybatis多个AND和OR混用注意事项

mysql中AND的优先级高于OR,所以在查询时,会优先执行AND条件,除非使用()来将一个AND和OR括起来,这样才能使得OR得以按照语句的顺序执行。

如下图所示:

java测试代码

 @Test public void TestMutil(){ Species species = new Species(); ArrayList arrayList = new ArrayList(); arrayList.add("长喙蚤"); arrayList.add("尤氏"); List querySpeciesesListByMutilCondition = this.speciesMapper.querySpeciesesListByMutilCondition(arrayList, species.getEnglishName(), species.getHost(), species.getPosition(), species.getLocation(), species.getPhylum(), species.getClassName(), species.getOrder(), species.getFamily(), species.getJenus()); for (Species s : querySpeciesesListByMutilCondition) { System.out.println(s); } System.out.println(querySpeciesesListByMutilCondition.size()); }

Mapper文件中没有使用()放在语句中执行情况

 

Mapper文件中使用()放在语句中执行情况

 

补充:

如果这里使用多个%来解决上述的含有多个OR和AND情况,那么所实现功能会有问题,因为多个关键词有%来连接,会有一个次序问题。具体效果见下图

以上这篇mybatis and,or复合查询操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持html中文网。

以上就是mybatis and,or复合查询操作的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » Java