场景:
mybaits多个参数传递 按索引传递参数,但是报错!如下
nested exception is org.apache.ibatis.binding.BindingException: Parameter '0' not found. Available parameters are [arg1, arg0, param1, param2]
代码:没有问题啊,查证发现与mybaits的版本号有关
<update id="updateAuthGroup" >
update CFG_SYS_AUTH_GROUP set GROUP_NAME =#{0}, CREATOR=#{2},CREATE_TIME=CURRENT TIMESTAMP
where GROUP_ID=#{1}
</update>
原因:
注意这里的mybatis版本号
在MyBatis3.4.4版不能直接使用#{0}要使用 #{arg0} ,0是指参数的索引,从0开始。第一个参数是0,第二个参数是1,依次类推
解决:
<update id="updateAuthGroup" >
update CFG_SYS_AUTH_GROUP set GROUP_NAME =#{arg0}, CREATOR=#{arg2},CREATE_TIME=CURRENT TIMESTAMP
where GROUP_ID=#{arg1}
</update>
完美!成功执行操作,注意由于多个参数且参数类型不一致,所以这里不能使用parameterType
补充:
单个参数传递:
public List<XXBean> getXXBeanList(String xxCode);
<select id="getXXXBeanList" parameterType="java.lang.String" resultType="XXBean">
select t.* from tableName t where t.id= #{id}
</select>
其中方法名和ID一致,#{}中的参数名与方法中的参数名一直, 我这里采用的是XXXBean是采用的短名字,
select 后的字段列表要和bean中的属性名一致, 如果不一致的可以用 as 来补充。
map封装参数传递:
public List<XXXBean> getXXXBeanList(HashMap map);
<select id="getXXXBeanList" parameterType="hashmap" resultType="XXBean">
select 字段... from XXX where id=#{xxId} code = #{xxCode}
</select>
其中hashmap是mybatis自己配置好的直接使用就行。map中key的名字就是#{}中的值
多参数注解方式(索引方式已在上面说明):
public AddrInfo getAddrInfo(@Param("corpId")int corpId, @Param("addrId")int addrId);
<select id="getAddrInfo" resultType="map">
SELECT * FROM addr__info
where addr_id=#{addrId} and corp_id=#{corpId}
</select>
list参数传递
public List<XXXBean> getXXXBeanList(List<String> list);
<select id="getXXXBeanList" resultType="XXBean">
select 字段... from XXX where id in
<foreach item="item" index="index" collection="list" open="(" separator="," close=")">
#{item}
</foreach>
</select>
foreach 最后的效果是select 字段... from XXX where id in ('1','2','3','4')
彩蛋~~~补充 :foreach
关键字 | 使用 | 解释 |
collection | collection=”ids” | 参数是跟一个集合,这里的 ids就是需要遍历的集合的名称 |
open | open=”(“ | foreach 遍历开始拼接的字符串 |
close | close=”)” | foreach 遍历结束拼接的字符串 |
separator | separator=”,” | 遍历 item 之间的分割符 |
item | item=”type” | 遍历后 item 的名字 |
解释:
case
<foreach collection="types" open="(" close=")" separator="," item="type">
#{type, jdbcType=SMALLINT}
</foreach>
<!--如果不使用open,close,则需要自己加上"()"-->
<foreach collection="types" separator="," item="type">
( #{type, jdbcType=SMALLINT} )
</foreach>
假设 传入的 types 是 [0,1,2]
上面通过 foreach 遍历后完整的SQL 如下
and type in (0,1,2)