MyBatis中批量插入数据库与批量更新数据库的XML代码写法
下面以MySQL为例讲解。
一、批量插入(insert)
比较批量插入,批量更新要复杂些。
1. 普通写法
这种写法一条记录update一次,性能比较差,容易造成阻塞,不建议使用!
这种写法执行一次update,性能好,效率高,推荐使用。
下面是在MyBatis中的代码实现。
下面以MySQL为例讲解。
一、批量插入(insert)
DAO层接口定义:
int insertBatch(@Param("arrtest")TestEntity[] arrTest);
XML文件配置:
<insert id="insertBatch">
insert into TEST (STATE, TESTID, TYPE, COMMENT, STUID, PRTSN, BTIME, ETIME)
values
<foreach collection="arrtest" item="item" index="index" separator="," >
(#{item.state,jdbcType=TINYINT}, #{item.testid,jdbcType=BIGINT}, #{item.type,jdbcType=TINYINT},
#{item.comment,jdbcType=VARCHAR}, #{item.stuid,jdbcType=BIGINT}, #{item.prtsn,jdbcType=INTEGER}, NOW(), NOW())
</foreach>
</insert>
二、批量更新(update)
比较批量插入,批量更新要复杂些。
1. 普通写法
这种写法一条记录update一次,性能比较差,容易造成阻塞,不建议使用!
XML代码:
<update id="updateBatch" parameterType="java.util.List">
<foreach collection="list" item="item" index="index" open="" close="" separator=";">
update TEST
<set>
NAME=${item.name}
</set>
where TESTID = ${item.testid}
</foreach>
</update>
2. 使用“case when”语法来实现这个功能
这种写法执行一次update,性能好,效率高,推荐使用。
XML代码:
update TEST
SET NAME = case id
when 1 then 'name1'
when 2 then 'name2'
when 3 then 'name3'
end,
TITLE = case id
when 1 then 'new title 1'
when 2 then 'new title 2'
when 3 then 'new title 3'
end
where TESTID in (1,2,3)
这条SQL语句的意思是,如果TESTID为1,则NAME的值为name1,TITLE的值为“new title 1”,依此类推。
下面是在MyBatis中的代码实现。
DAO层接口定义:
int updateBatchByPrimaryKeySelective(@Param("arrtest")TestEntity[] arrTest);
XML文件配置:
<update id="updateBatchByPrimaryKeySelective">
update TEST
<trim prefix="set" suffixOverrides=",">
<trim prefix="STATE = case" suffix="end,">
<foreach collection="arrtest" item="item" index="index">
<choose>
<when test="item.state != null">
when TESTID = #{item.testid} then #{item.state}
</when>
<otherwise>
when TESTID = #{item.testid} then STATE
</otherwise>
</choose>
</foreach>
</trim>
<trim prefix="NAME = case" suffix="end," >
<foreach collection="arrtest" item="item" index="index">
<choose>
<when test="item.name != null">
when TESTID = #{item.testid} then #{item.name}
</when>
<otherwise>
when TESTID = #{item.testid} then NAME
</otherwise>
</choose>
</foreach>
</trim>
<trim prefix="BTIME = case" suffix="end," >
<foreach collection="arrtest" item="item" index="index">
<choose>
<when test="item.btime != null">
when TESTID = #{item.testid} then #{item.btime}
</when>
<otherwise>
when TESTID = #{item.testid} then BTIME
</otherwise>
</choose>
</foreach>
</trim>
</trim>
where
<foreach collection="arrtest" separator="or" item="item" index="index">
TESTID = #{item.testid}
</foreach>
</update>
Ok,完毕!