1.场景:
在直连酒店静态信息更新JOB执行数据比对、推送资源系统成功之后,之前对旧数据进行的是逻辑删除,随着酒店数量逐渐增大数据库压力剧增,后面决定物理删除旧数据。单线程执行没问题,几个酒店并发执行更新时,数据库出现死锁。
MySQL版本为: 5.6.38 MySQL Community Server (GPL)
事务隔离级别为MySQL默认:RR (Repeatable Read)
报错报文样例如下:
### Error updating database. Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLTransactionRollbackException: Deadlock found when trying to get lock; try restarting transaction
### The error may involve com.banma.ota.mapper.hotel.DescriptionDoMapper.deleteByHotelInfoId-Inline
### The error occurred while setting parameters
### SQL: delete from ota_policy_info where ota_policy_info.policy_id in (select p.id from ota_hotel_info h,ota_policy p where h.id=p.hotel_info_id and h.id=?)
### Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLTransactionRollbackException: Deadlock found when trying to get lock; try restarting transaction; SQL []; Deadlock found when trying to get lock; try restarting transaction; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLTransactionRollbackException: Deadlock found when trying to get lock; try restarting transaction
2.删除表数据的逻辑如下:
分为两种情况
a.通过hotel_code查出hotel_info表的自增id,再通过该id删除其他几张表
b.policy表与policy_info表、address表与address_zone表存在里外联系处理方法为先根据hotel_info_id找到policy表对应的policy_id,根据policy_id先删除policy_info表再删除policy表。
3.产生报错的几个SQL整理如下
(以下SQL均不是本人所写 = ,=)
delete from ota_hotel_room_type where ota_hotel_room_type.hotel_info_id=(select id from ota_hotel_info where id=?)
delete from ota_contact_info where ota_contact_info.hotel_info_id =(select id from ota_hotel_info where id=?)
delete from ota_affiliation_info where ota_affiliation_info.hotel_info_id=(select id from ota_hotel_info where id=?)
delete from ota_contact_info where ota_contact_info.hotel_info_id =(select id from ota_hotel_info where id=?)
delete from ota_address_zone where ota_address_zone.address_id in (select a.id from ota_hotel_info h,ota_hotel_address a where h.id=a.hotel_info_id and h.id=?)