mybatis 批量插入,报唯一索引字段重复插入 Duplicate entry
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '057f31082f1c4534af4c2d5f334c6124' for key 'uni_trans'
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
at com.mysql.jdbc.Util.getInstance(Util.java:408)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:936)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3978)
解答:综上所示,其实批量的数据是不重复的,而插入操作却报了某个值重复插入,查了一个解决方式也亲测可用。
1 数据库连接字符串 必须配置 allowMultiQueries=true
如 jdbc:mysql://192.168.166.181:3306/promotion?allowMultiQueries=true&autoReconnect=true&useSSL=false&characterEncoding=utf-8
2 插入sql语句中 加入ignore关键字
如
<insert id="batchSaveFinale" parameterType="java.util.List" useGeneratedKeys="true" keyProperty="id">
insert ignore into tpromotion_finalist
(
user_id,
transac_id,
phone,
create_time
)
values
<foreach item="item" collection="list" separator="," >
(
#{item.userId},
#{item.transacId},
#{item.phone},
#{item.createTime}
)
</foreach>
</insert>