場景:
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)