当前位置: 移动技术网 > IT编程>开发语言>Java > Mybatis 插入和删除批处理操作

Mybatis 插入和删除批处理操作

2019年07月22日  | 移动技术网IT编程  | 我要评论

在操作数据库时,经常会碰到批量插入、批量删除的情况,直接执行sql语句还好做一点,当使用mybatis进行批量插入、批量删除时会有一些问题。下面对使用mybatis批量插入,批量删除进行介绍。

1. 批量插入

java代码:

// model: test.java
@data
public class test {
private string x;
private string y;
private string z;
}
// mapper: testmapper.java
public void inserttestlist(list<test> testlist);

xml代码

<!-- xml: testmapper.xml -->
...
<!-- 忽略重复数据 -->
<insert id="inserttestlist" parametertype="test">
insert ignore into 
test_table(test_x, test_y, test_z)
values
<foreach item="item" index="index" collection="list" open="(" close=")" separator=",">
#{item}.x, #{item.y}, #{item}.z
</foreach>
</insert>
<!-- 更新重复数据 -->
<insert id="inserttestlist" parametertype="test">
insert into 
test_table(test_x, test_y, test_z)
values
<foreach item="item" index="index" collection="list" open="(" close=")" separator=",">
#{item}.x, #{item.y}, #{item}.z
</foreach>
on duplicate key update
test_x = values(test_x),
test_y = values(test_y),
test_z = values(test_z)
</insert>
...

批量插入sql语句

insert into test_table(x, y, z) values (1, 1, 1), (2, 2, 2), (3, 3, 3)

备注:value()是mysql的一个函数,具体解释可以查看文档function_values。

主要功能就是在数据重复时可以获取要更新的值。

2. 批量删除

java代码:

// model: test.java
@data
public class test {
private string x;
private string y;
private string z;
}
// mapper: testmapper.java
public void deletetestlist(list<test> testlist);

xml代码

<!-- xml: testmapper.xml -->
...
<delete id="deletetestlist" parametertype="test">
delete from 
test_table
where
<foreach item="item" index="index" collection="list" open="(" close=")" separator="or">
test_x = #{item.x} and test_y = #{item.y} and test_z = #{item.z}
</foreach>
</delete>
...

sql语句

delete from test_table where (test_x = 1 and test_y = 1 and test_z = 1) or (test_x = 2 and test_y = 2 and test_z = 2) or (test_x = 3 and test_y = 3 and test_z = 3)

备注:上面的代码为x,y,z为联合主键的情况,普通情况使用where id in。

以上所述是小编给大家介绍的mybatis 插入和删除批处理操作,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网