foreach标签的collection属性的取值
传的是List列表
接口代码
- List<Emp> findEmpByDeptnos(List<Integer> deptnos);
xml配置代码
- <select id="findEmpByDeptnos" resultType="Emp" parameterType="list">
- ? ? SELECT * FROM emp e
- ? ? WHERE e.deptno IN
- ? ? <foreach collection="list" item="deptno" open="(" separator="," close=")">
- ? ? ? ? #{deptno}
- ? ? </foreach>
- </select>
传的是Array数组
接口代码
- List<Emp> findEmpByDeptnos(Integer[] deptnos);
xml配置代码
- <select id="findEmpByDeptnos" resultType="Emp" parameterType="int">
- ? ? SELECT * FROM emp e
- ? ? WHERE e.deptno IN
- ? ? <foreach collection="array" item="deptno" open="(" separator="," close=")">
- ? ? ? ? #{deptno}
- ? ? </foreach>
- </select>
传的是Map
接口代码
- List<Emp> findEmpByDeptnos(Map<String,List<Integer>> deptnos);
xml配置代码
- <select id="findEmpByDeptnos" resultType="Emp" parameterType="map">
- ? ? SELECT * FROM emp e
- ? ? WHERE e.deptno IN
- ? ? <foreach collection="myKey" item="deptno" open="(" separator="," close=")">
- ? ? ? ? #{deptno}
- ? ? </foreach>
- </select>
collection属性总结
- 如果传入的参数是List,则填写list
- 如果传入的参数是数组形式,则填写array
- 如果是多参数传参,传的是map,则填写列表的键key
MyBatis使用foreach标签报错
在使用mybatis过程中,<foreach>标签算是比较常用的,最近在项目中遇到这样一个问题,使用<foreach>标签循环拼接SQL语句时
报了一个错误:
nested exception is org.apache.ibatis.reflection.ReflectionException: There is no getter for property named ‘__frch_name_0’ in ‘class com.stand.modules.address.param.GeneralAddressQueryParam’
比较疑惑,这个标签使用了很多次了,还是第一次遇到这样的问题,通过查阅资料,得到了解决方案。
原因
首先贴出涉及到的实体类、Mapper接口和对应的XML部分代码
用于Mapper接口传参的实体类:
- public class GeneralAddressQueryParam implements Serializable {
-
- ? ? /**
- ? ? ?* 地名,多级地名用逗号分隔
- ? ? ?*/
- ? ? private String names;
-
- ? ? /**
- ? ? ?* 多地名查询条件
- ? ? ?*/
- ? ? private List<String> nameList;
-
- ? ? public String getNames() {
- ? ? ? ? return names;
- ? ? }
-
- ? ? public void setNames(String names) {
- ? ? ? ? this.names = names;
- ? ? }
-
- ? ? public List<String> getNameList() {
- ? ? ? ? return nameList;
- ? ? }
-
- ? ? public void setNameList(List<String> nameList) {
- ? ? ? ? this.nameList = nameList;
- ? ? }
- }
Mapper接口
- List<GeneralAddressFullNameDTO> multiNameQuery(GeneralAddressQueryParam queryParam);
XML部分代码
- <if test="nameList != null and nameList.size() > 0">
- ? ? <foreach collection="nameList" item="name">
- ? ? ?? ?and address like concat('%', #{name}, '%')
- ? ? </foreach>
- </if>
以上就是问题涉及到的部分代码,出错的原因呢,就是在<foreach>标签中取值出的错,网上查阅资料说是因为parameterType接收的参数不是List导致的,具体情况未核实。
解决方案
解决方法比较简单,或一种取值方式即可,将<foreach>标签中遍历出来的值换做如下方式获取
- <if test="nameList != null and nameList.size() > 0">
- ? ? <foreach collection="nameList" item="name" index="index">
- ? ? ?? ?and address like concat('%', #{nameList[${index}]}, '%')
- ? ? </foreach>
- </if>
以上为个人经验,希望能给大家一个参考,也希望大家多多支持w3xue。