我有一张表trade_order:
CREATE TABLE `trade_order` IF NOT EXISTS `buyer_order` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`order_no` varchar(30) NOT NULL DEFAULT '',
`name` int(11) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
UNIQUE KEY `order_no` (`order_no`),
)
现在我想将数据插入表trade_order。我是这样做的:
transaction begin.
===
result = select * from order_table where order_no = #{orderNo} for update
if(result is null){
insert into trade_order (order_no,name) values (orderNo,name)
}
else{
update trade_order set name = #{name} where order_no = #{orderNo}
}
===
transaction end.
但我得到了死锁:
org.springframework.dao.DeadlockLoserDataAccessException:
### 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.youzan.trade.process.datasync.dal.dao.OrderDAO.insert-Inline
### The error occurred while setting parameters
### SQL: insert into trade_order ( order_no, name ) values ( ?, ?, )
### 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
两个线程可能同时处理相同的两个数据,并且两个线程都执行插入操作。
但它会导致deadLock吗?我想知道为什么。
(mysql事务隔离级别是RR,InnoDB引擎)