有时我们需要批量想数据库中插入数据,如果通过循环一条一条的向数据库中插入,数据量大时容易造成阻塞,不建议使用。其实mybatis自身有很好的实现方式
1、批量插入
<insert id="batchInsertCoursePlan" parameterType="java.util.List" >
<selectKey resultType="Integer" keyProperty="id" order="BEFORE">
SELECT COURSEARRANGEMENT_SQ.NEXTVAL FROM dual
</selectKey>
INSERT INTO XTEL_CourseArrangement(ID, COURSEID,TIME,CLASSNUMBER)
SELECT COURSEARRANGEMENT_SQ.NEXTVAL, m.* FROM(
<foreach collection="list" index="index" item="coursePlan" separator="union all">
select
#{coursePlan.courseID} as COURSEID,
#{coursePlan.time} as TIME,
#{coursePlan.classNumber} as CLASSNUMBER
from dual
</foreach>
)m
</insert>
2、批量更新
<update id="updateBatch" parameterType="java.util.List">
<foreach collection="list" item="item" index="index" open="begin" close=";end;" separator=";">
update T_CITY_INDEX t
set
t.city_name= #{item.cityName,jdbcType=VARCHAR} ,
t.district_name= #{item.districtName,jdbcType=VARCHAR} ,
where t.id = #{item.id,jdbcType=NUMERIC}
</foreach>
</update>