<!-- 這次用resultmap接收輸出結果 --> <select id="findByName" parameterType="string" resultMap="customerMap"> select * from t_customer where c_name like concat('%', #{name},'%') order by c_ceroNo limit 0,100 </select> <!-- 批量更新第一種方法,通過接收傳進來的參數list進行循環着組裝sql --> <update id="batchUpdate" parameterType="java.util.Map"> <!-- 接收list參數,循環着組裝sql語句,注意for循環的寫法 separator=";" 代表着每次循環完,在sql后面放一個分號 item="cus" 循環List的每條的結果集 collection="list" list 即為 map傳過來的參數key --> <foreach collection="list" separator=";" item="cus"> update t_customer set c_name = #{cus.name}, c_age = #{cus.age}, c_sex = #{cus.sex}, c_ceroNo = #{cus.ceroNo}, c_ceroType = #{cus.ceroType} where id = #{cus.id} </foreach> </update> <!-- 批量更新第二種方法,通過 case when語句變相的進行批量更新 --> <update id="batchUpdateCaseWhen" parameterType="java.util.Map"> update t_customer <trim prefix="set" suffixOverrides=","> <!-- 拼接case when 這是一種寫法 --> <!--<foreach collection="list" separator="" item="cus" open="c_age = case id" close="end, ">--> <!--when #{cus.id} then #{cus.age}--> <!--</foreach>--> <!-- 拼接case when 這是另一種寫法,這種寫着更專業的感覺 --> <trim prefix="c_name =case" suffix="end,"> <foreach collection="list" item="cus"> <if test="cus.name!=null"> when id=#{cus.id} then #{cus.name} </if> </foreach> </trim> <trim prefix="c_age =case" suffix="end,"> <foreach collection="list" item="cus"> <if test="cus.age!=null"> when id=#{cus.id} then #{cus.age} </if> </foreach> </trim> <trim prefix="c_sex =case" suffix="end,"> <foreach collection="list" item="cus"> <if test="cus.sex!=null"> when id=#{cus.id} then #{cus.sex} </if> </foreach> </trim> <trim prefix="c_ceroNo =case" suffix="end,"> <foreach collection="list" item="cus"> <if test="cus.ceroNo!=null"> when id=#{cus.id} then #{cus.ceroNo} </if> </foreach> </trim> <trim prefix="c_ceroType =case" suffix="end,"> <foreach collection="list" item="cus"> <if test="cus.ceroType!=null"> when id=#{cus.id} then #{cus.ceroType} </if> </foreach> </trim> </trim> <where> <foreach collection="list" separator="or" item="cus"> id = #{cus.id} </foreach> </where> </update>
int batchUpdate(Map<String,Object> param); int batchUpdateCaseWhen(Map<String,Object> param);
第一種效率其實相當高的,因為它僅僅有一個循環體,只不過最后update語句比較多,量大了就有可能造成sql阻塞。注意第一種方法要想成功,需要在db鏈接url后面帶一個參數 &allowMultiQueries=true 即: jdbc:mysql://localhost:3306/mysqlTest?characterEncoding=utf-8&allowMultiQueries=true
第二種雖然最后只會有一條更新語句,但是xml中的循環體有點多,每一個case when 都要循環一遍list集合,所以大批量拼sql的時候會比較慢,所以效率問題嚴重。使用的時候建議分批插入。
原文鏈接:https://blog.csdn.net/xu1916659422/article/details/77971696