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>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章