更新時(shí)間:2021-07-06 16:30:03 來(lái)源:動(dòng)力節(jié)點(diǎn) 瀏覽1067次
在項(xiàng)目中遇到了需要批量操作數(shù)據(jù)表的情況,小編遇到的是更新操作。但在mybatis中批量操作有多種,因此在此對(duì)mybatis中的批量操作以及其注意點(diǎn)進(jìn)行總結(jié)。
1.批量插入操作
批量插入,傳入的是一個(gè)List對(duì)象的集合,因此在mapper文件中需要用循環(huán)的方式進(jìn)行操作,具體格式如下:
<insert id="insertBatch" parameterType="java.utils.List">
insert into tablename (xxx,xxx,xxx)
values
/*collection的屬性值為接口中對(duì)應(yīng)的參數(shù)名稱
(#{item.xxx},#{item.xxx},#{item.xxx}
通過(guò)屬性的方式取得對(duì)應(yīng)的值,注意小括號(hào)的使用
*/
<foreach collection="listxxx" item="item" separator=",">
(#{item.xxx},#{item.xxx},#{item.xxx})
</foreach>
</insert>
mapper文件對(duì)應(yīng)的接口形式如下:
public void insertBatch(@Param("listxxx") List<xxx> listxxx);
2.批量更新操作
批量更新操作,筆者總結(jié)了下面兩種方式:
(1)使用循環(huán)update形式【這種方式需要特別注意,需要在數(shù)據(jù)庫(kù)連接字符串中增加allowMultiQueries=true,不然會(huì)報(bào)異常】
<update id="batchUpdate" parameterType="java.util.List">
<foreach collection="list" index="index" item="item" separator=";">
update t_demo_user set
<if test="item.userName!=null">
user_name=#{item.userName},
</if>
<if test="item.gender!=null">
gender=#{item.gender}
</if>
where user_id=#{item.userId}
</foreach>
</update>
(2)使用 case 形式
<update id="batchUpdate" parameterType="java.util.List">
UPDATE t_demo_user
<trim prefix="set" suffixOverrides=",">
<trim prefix="user_name= case" suffix="end,">
<foreach collection="list" item="item" index="index">
<if test="item.userName !=null">
when user_id=#{item.userId} then #{item.userName}
</if>
</foreach>
</trim>
<trim prefix="gender= case" suffix="end,">
<foreach collection="list" item="item" index="index">
<if test="item.gender !=null">
when user_id=#{item.userId} then #{item.gender}
</if>
</foreach>
</trim>
</trim>
where user_id in
<foreach collection="list" item="item" index="index" separator="," open="(" close=")">
#{item.userId}
</foreach>
</update>
以上就是動(dòng)力節(jié)點(diǎn)小編介紹的"MyBatis批量的詳細(xì)操作",希望對(duì)大家有幫助,想了解更多可查看Mybatis基礎(chǔ)教程,如有疑問(wèn),請(qǐng)?jiān)诰€咨詢,有專業(yè)老師隨時(shí)為您服務(wù)。
0基礎(chǔ) 0學(xué)費(fèi) 15天面授
有基礎(chǔ) 直達(dá)就業(yè)
業(yè)余時(shí)間 高薪轉(zhuǎn)行
工作1~3年,加薪神器
工作3~5年,晉升架構(gòu)
提交申請(qǐng)后,顧問(wèn)老師會(huì)電話與您溝通安排學(xué)習(xí)
初級(jí) 202925
初級(jí) 203221
初級(jí) 202629
初級(jí) 203743