mybatis批量更新或插入

示例:

Service层代码

        /**
* 批量新增区划代码记录
* @param entity
*/
@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
public void insertBatch(List<SyncAreaCode> list) throws Exception{
dao.insertBatch(list);
}

/**
* 批量更新区划代码记录
* @param entity
*/
@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
public void updateBatch(List<SyncAreaCode> list) throws Exception{
dao.updateBatch(list);

}


mybatis的xml代码

        <!-- 批量新增区划代码记录 -->
<insert id="insertBatch" parameterType="java.util.List">
INSERT INTO cga_areacode (
area_id, area_name, area_code, area_level, parent_id
)
<foreach collection="list" item="item" index="index"  close=")" open="(" separator="union">
SELECT  
#{item.areaId,jdbcType=VARCHAR}, 
#{item.areaName,jdbcType=VARCHAR}, 
#{item.areaCode,jdbcType=VARCHAR}, 
#{item.areaLevel,jdbcType=VARCHAR},
#{item.parentId,jdbcType=VARCHAR}
FROM dual
</foreach>
</insert>

<!-- 批量更新区划代码记录 -->
<update id="updateBatch"  parameterType="java.util.List">
   <foreach collection="list" item="item" index="index" open="begin" close=";end;" separator=";">
       UPDATE cga_areacode  
<set>
           <if test="item.areaName != null and item.areaName != ''">
area_name = #{item.areaName,jdbcType=VARCHAR},
</if>
<if test="item.areaCode != null and item.areaCode != ''">
area_code = #{item.areaCode,jdbcType=VARCHAR},
</if>
<if test="item.areaLevel != null and item.areaLevel != ''">
area_level = #{item.areaLevel,jdbcType=VARCHAR},
</if>
<if test="item.parentId != null and item.parentId != ''">
parent_id = #{item.parentId,jdbcType=VARCHAR},
</if>
            </set>
       where area_id = #{item.areaId,jdbcType=VARCHAR}
   </foreach>
</update>

猜你喜欢

转载自blog.csdn.net/fantasy522272820/article/details/79814312