解决Mybatis mappe同时传递 List 和其他参数报错的问题
作者:严格格
在使用MyBatis时,如果需要传递多个参数到SQL中,可以遇到参数绑定问题,解决方法包括使用@Param注解和修改mapper.xml配置,感兴趣的朋友跟随小编一起看看吧
问题描述:
想要实现这个接口,同时传入planId和projectPlans,屡次报错。好在一路坎坷,解决了多方bug,最后终于搞定了
void insertList(@Param("planId") Integer planId, @Param("projectPlans") List<ProjectPlan> projectPlans);
1 刚开始爆绑定失败
后来发现原来是我的xml文件没有写mapper后缀
2 多个参数传值用@Param失败
别人说用这个,但是发现根本不行,
void insertList(@Param("planId") Integer planId, @Param("projectPlans") List<ProjectPlan> projectPlans);
<insert id="insertList" parameterType="java.util.Map"> insert into nursing_project_plan (plan_id,project_id,execute_time,execute_cycle, execute_frequency,create_by, update_by, create_time, update_time,remark) values <foreach collection="projectPlans" item="project" separator=","> (#{planId},#{project.projectId},#{project.executeTime},#{project.executeCycle}, #{project.executeFrequency},#{project.createBy},#{project.updateBy},#{project.createTime},#{project.updateTime},#{project.remark} ) </foreach> </insert>
解决思路
报错信息
org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.binding.BindingException: Parameter 'customerIdList' not found. Available parameters are [arg0, collection, list]
解释:
解释:
当我们传递一个 List 实例或者数组作为参数对象传给 MyBatis。当你这么做的时候,MyBatis 会自动将它包装在一个 Map 中,用名称在作为键。List 实例将会以list 作为键,而数组实例将会以array作为键。所以,当我们传递的是一个List集合时,mybatis会自动把我们的list集合包装成以list为Key值的map。
错误代码:
mapper层
void insertList(List<ProjectPlan>projectPlans ); //这个方法也是会错 void insertList(List<ProjectPlan>projectPlans ,Integer planId);
xml层
<insert id="insertList" > insert into nursing_project_plan (plan_id,project_id,execute_time,execute_cycle, execute_frequency,create_by, update_by, create_time, update_time,remark) values <foreach collection="projectPlans" item="project" separator=","> (#{planId},#{project.projectId},#{project.executeTime},#{project.executeCycle}, #{project.executeFrequency},#{project.createBy},#{project.updateBy},#{project.createTime},#{project.updateTime},#{project.remark} ) </foreach> </insert>
解决方法
service层
(封装成map)
Map maps = new HashMap(); maps.put("projectPlans", projectPlans); maps.put("planId", 2); nursingProjectPlanMapper.insertList(maps);
mapper层
void insertList( Map maps);
xml层
<insert id="insertList" parameterType="java.util.Map"> insert into nursing_project_plan (plan_id,project_id,execute_time,execute_cycle, execute_frequency,create_by, update_by, create_time, update_time,remark) values <foreach collection="projectPlans" item="project" separator=","> (#{planId},#{project.projectId},#{project.executeTime},#{project.executeCycle}, #{project.executeFrequency},#{project.createBy},#{project.updateBy},#{project.createTime},#{project.updateTime},#{project.remark} ) </foreach> </insert>
成功了
到此这篇关于解决Mybatis mappe同时传递 List 和其他参数报错的问题的文章就介绍到这了,更多相关Mybatis mappe传递 List 报错内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!