事情是这样的,博主刚刚写完一个小项目,由于使用的量比较大,所以做了一下压测,在插入数据的时候报出了如下错误 :
[http-bio-****-exec-67] DEBUG c.j.m.a.d.A.insertAppUser!selectKey - ==> Parameters:
org.springframework.dao.DuplicateKeyException:
### Error updating database. Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '236533' for key 'PRIMARY'
很显然高并发下主键冲突了,开始漫长的找寻原因。最终发现
insert id="insertCustomerLog" parameterType="java.util.Map" useGeneratedKeys="true">
<!-- <selectKey resultType="java.lang.Long" keyProperty="dto.id" order="BEFORE">
select auto_increment from information_schema.tables where table_name='***' and table_schema=schema();
</selectKey> -->
insert into ****
主键是查询后在插入的时候是先查询的。这样高并发下就有了。间隙。
最终解决 useGeneratedKeys="true" keyProperty="id" 加上这个 去掉
<!-- <selectKey resultType="java.lang.Long" keyProperty="dto.id" order="BEFORE">
select auto_increment from information_schema.tables where table_name='***' and table_schema=schema();
</selectKey> -->
虽然都在一个事物里。都是还会发生查询间隙这个问题 并发200