本文小编为大家详细介绍“MyBatis中foreach标签的collection属性取值方式是什么”,内容详细,步骤清晰,细节处理妥当,希望这篇“MyBatis中foreach标签的collection属性取值方式是什么”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。
接口代码
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>
接口代码
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>
接口代码
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>
如果传入的参数是List,则填写list
如果传入的参数是数组形式,则填写array
如果是多参数传参,传的是map,则填写列表的键key
在使用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>
读到这里,这篇“MyBatis中foreach标签的collection属性取值方式是什么”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。