解决Mybatis中foreach嵌套使用if标签对象取值的问题
作者:_修铁路的 时间:2023-11-23 06:02:02
foreach嵌套使用if标签对象取值问题
最近做项目过程中,涉及到需要在 Mybatis 中 使用 foreach 进行循环读取传入的查询条件,动态拼接SQL语句,接口传入的查询条件格式:{"advanceSearchList":[{"searchType":10,"searchText":"12"}]} ,根据我定义的参数格式,需要在 Mybatis中动态去循环读取 advanceSearchList 集合中的json对象,并根据 json对象中的 searchType 做不同的处理,需要在 foreach 中嵌套 if 标签进行判断使用。
大体格式
<foreach collection="advanceSearchList" item="item" index="index" >
<if test="xxx == 10 ">
and abc like CONCAT('%', ddd, '%')
</if>
</foreach>
因为当前 foreach 中获取到的 item 是一个json对象,涉及到在 if 标签中获取当前对象中指定属性的值,一时脑抽,没有想起来取值办法,咨询万能的度娘没有得到满意的回复,经过自己傻瓜式的尝试,终于找到了取值方法,特此记录下:
解决办法
Mybatis 在 foreach 标签中使用 if 标签获取对象属性方法:
直接通过 对象.属性 的方式获取!!!!对,你没看错,就是直接通过 对象.属性 的方式获取!!!
例如:当前foreach 循环获取的对象是 item,想要获取对象中的 searchType ,直接就是 item.searchType 即可……
代码如下
<foreach collection="advanceSearchList" item="item" index="index" >
<if test="item.searchType == 10 ">
and abc like CONCAT('%', #{item.searchText}, '%')
</if>
</foreach>
Mybatis if 语句嵌套
在使用mybatis的时候,可以在 if 标签下面加上if标签。
比如要对这个sql语句进行改进。
select a.* from emp a
inner join dept b
on a.deptno = b.no
where b.place= #{place}
要求
如果 传入的 地点 是 North Korea 那么 符合 a中的条件也可以。
a.male = 'M' or a.age bewteen 20 and 30
where语句可以这么写
select * from emp e
<where>
<if test="_parameter.place != null and _parameter.place != '' ">
and
<if test="_parameter.place == 'North Korea' "> ( </if>
b.place = #{place}
<if test="_parameter.place == 'North Korea' ">
or a.male = 'M' or a.ge between 20 and 30 )
</if>
</if>
</where>
注意里面的括号。
来源:https://blog.csdn.net/sinat_35626559/article/details/106252332
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Android Spinner 下拉菜单的使用
实例讲解JAVA设计模式之备忘录模式
Android滑动冲突的完美解决方案
![](https://img.aspxhome.com/file/2023/7/137217_0s.gif)
搞懂Java线程池
![](https://img.aspxhome.com/file/2023/5/62345_0s.jpg)
Java单例模式简单示例
![](https://img.aspxhome.com/file/2023/3/61843_0s.png)
java中javamail发送带附件的邮件实现方法
Android仿微信QQ设置图形头像裁剪功能
![](https://img.aspxhome.com/file/2023/9/137719_0s.gif)
java定时任务Timer和TimerTask使用详解
C#自定义针对URL地址的处理类实例
详解Java后端优雅验证参数合法性
![](https://img.aspxhome.com/file/2023/9/60159_0s.jpg)
java链式创建json对象的实现
svn 清理失败 (cleanup 失败) 的快速解决方法
![](https://img.aspxhome.com/file/2023/3/60843_0s.jpg)
Android 中的两端对齐实例详解
为Android的apk应用程序文件加壳以防止反编译的教程
![](https://img.aspxhome.com/file/2023/8/139058_0s.png)
Java中File类方法详解以及实践
![](https://img.aspxhome.com/file/2023/5/65605_0s.jpg)
在C#和Java语言中for和foreach的区别详解
Input系统之InputReader处理按键事件详解
Android实现应用内置语言切换功能
![](https://img.aspxhome.com/file/2023/6/138526_0s.jpg)
Java8中的Stream 流实践操作
![](https://img.aspxhome.com/file/2023/0/87210_0s.webp)
Java JDK动态代理(AOP)用法及实现原理详解
![](https://img.aspxhome.com/file/2023/2/69292_0s.png)