MyBatis使用-传递参数注意事项
返回导航页
使用Map传递参数
Map params = new HashMap<>();
params.put("gender",gender);
params.put("age",age);
XML,直接取就行
select * from XXXX where gender = #{gender} and age = #{age}
参考这个老哥总结的
常见传递参数方式
遇到的问题:
传参为数组或者list的错误,应该处理方式
然后上网查了一下,还有一种说法是:
因为 传递一个 List 实例或者数组作为参数对象传给 MyBatis,MyBatis 会自动将它包装在一个 Map 中,用名称在作为键。List 实例将会以“list” 作为键,而数组实例将会以“array”作为键
接着我恢复了之前发生错误的环境,把xml中的foreach中的collection改成了list,其他的都没改,没有报错,也可以查询出结果。
因此,解决这个异常的两种方式是:
1.在方法参数前面加上你遍历的集合的名称,比如你在foreach的collection中写的是noList,那么你就在传入的list参数前面加上一个注解@Param(“noList”)。
2.将foreach的collection中的值改成list即可。
模糊查询
XML
<if test="supName != null">
and sup_name like CONCAT('%', #{supName},'%')
</if>
IN 关键字(多选)搜索,传递List
XML
<if test="rStatus != null">
and _status in(
<foreach collection="rStatus" index="index" item="tag" separator=",">
#{tag}
</foreach>
)
</if>
批量插入
dao层
Integer batchInsert(@Param("list") List<Object> list);
xml文件
insert into mysql_table_test(
<trim suffix="" suffixOverrides=",">
service_name
queue_type,
service_type
</trim>
)
values
<foreach collection="list" item="item" index="index" separator=",">
(
<if test="item.serviceName != null">
#{item.serviceName},
</if>
<if test="item.serviceName == null">
NULL ,
</if>
<if test="item.queueType !=null">
#{item.queueType},
</if>
<if test="item.serviceType !=null">
#{item.serviceType},
</if>
</trim>
)
</foreach>
</insert>```