Mybatis-plus批量去重插入 ON DUPLICATE key update的用法

1.添加唯一索引【用来判断数据库是否有重复的标志】
这里的唯一索引可以是多个字段,也可以是唯一字段,这里我用name和password作为唯一标识
Mybatis-plus批量去重插入 ON DUPLICATE key update的用法_第1张图片
2.同时表对应的pojo类上字段也要加注解

@Data
@TableName("admin")
public class AdminEntity implements Serializable {
    private static final long serialVersionUID = 244947848024328503L;
    /**
     * 主键id
     */
    @TableId(type = IdType.AUTO)
    private Long id;
    private String name;
    private String password;
}

3.AdminMapper.java

public interface TestMapper extends SuperMapper<AdminEntity > {
    void saveAll(List<AdminEntity > list);
}

4.AdminMapper.xml


DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.hxj.test.mapper.AdminMapper">
    <insert id="saveAll">
        insert into admin(name,password)
        values
        <foreach collection="list" item="item" separator=",">
            (#{item.name},#{item.password})
        foreach>
        ON DUPLICATE key update
        name=values(name),
        password=values(password)
    insert>
mapper>

你可能感兴趣的:(mybatis,java,mysql)