mybatis批量插入如果存在就不插入
可以使用Mybatis的批量插入和动态SQL语句来实现这个功能。
例如,假设我们有一个表格叫做user,其中有id和name两个字段。我们需要批量插入一些用户信息,但是如果用户已经存在于表格中,则不进行插入操作。
首先,在Mapper接口中定义一个批量插入方法:
void batchInsert(@Param("users") List<User> users);
然后,在Mapper.xml中编写动态SQL语句:
<insert id="batchInsert" parameterType="map">
insert into user (id, name)
values
<foreach collection="users" item="user" separator=",">
<if test="user.id != null and user.name != null">
(#{user.id}, #{user.name})
</if>
</foreach>
on duplicate key update name = values(name)
</insert>
这个SQL语句使用了foreach标签来循环遍历插入的用户列表,使用if标签来判断用户id和name是否为空,如果不为空则插入到表格中。最后使用了MySQL的on duplicate key update语句来在插入时判断是否已经存在于表格中,如果存在则更新name字段。
最后,调用批量插入方法即可:
List<User> users = new ArrayList<>();
// 添加一些用户信息到users列表中
mapper.batchInsert(users);
``
原文地址: https://www.cveoy.top/t/topic/fhZm 著作权归作者所有。请勿转载和采集!