Mybatis+xml 批量操作(插入+更新)
Mybatis xml批量插入批量更新主键填充获取方式:前缀 + UUIDauto_increment批量插入sqlinsert into table (字段一,字段二) values(xx,xx),(oo,oo)mybatis xml<!-- 批量插入数据 查询主键ID注入到是实体中--><insert id="insertBatch" parameterType="java.
·
Mybatis xml
批量插入
- sql
insert into table (字段一,字段二) values(xx,xx),(oo,oo)
- mybatis xml
<!-- 批量插入数据 查询主键ID注入到是实体中-->
<insert id="insertBatch" parameterType="java.util.List" useGeneratedKeys="true">
<selectKey resultType="long" keyProperty="id" order="AFTER">
SELECT
LAST_INSERT_ID()
</selectKey>
insert into tablename
(id, field_name)
values
<foreach collection="list" item="item" index="index" separator=",">
(#{item.id},#{item.field_name})
</foreach>
</insert>
批量更新
- sql
UPDATE t_user
SET
age = CASE id
WHEN 1 THEN 10
WHEN 2 THEN 34
END,
name = CASE id
WHEN 1 THEN '大娃'
WHEN 2 THEN '二娃'
END
WHERE id IN (1,2)
- xml
<!-- 批量更新数据 -->
<update id="updateBatch">
update table_name set
name =
<foreach collection="list" item="item" index="index"
separator=" " open="case id" close="end">
when #{item.id} then #{item.name}
</foreach>
where id in
<foreach collection="list" item="item" index="index"
separator="," open="(" close=")">
#{item.id}
</foreach>
</update>
主键填充获取方式:
<selectKey keyProperty="tableId" resultType="string" order="BEFORE">
SELECT
CONCAT(
'PRE',
REPLACE ( UUID(), '-', '' ))
FROM
DUAL
</selectKey>
说明:将插入数据的主键注入到 user 对象中。
属性 | 说明 |
---|---|
LAST_INSERT_ID(): | 得到刚 insert 进去记录的主键值,只适用与自增主键 |
keyProperty: | 将查询到主键值设置到 parameterType 指定的对象的那个属性 |
order: | SELECT LAST_INSERT_ID() 执行顺序,相对于 insert 语句来说它的执行顺序 |
resultType: | 指定 SELECTLAST_INSERT_ID() 的结果类型 |
<selectKey resultType="long" keyProperty="id" order="AFTER">
SELECT
LAST_INSERT_ID()
</selectKey>
更多推荐
已为社区贡献6条内容
所有评论(0)