I am try to understand transactions using Spring Boot, Spring Data and MySQL.
I created service UpdateService
which is used to update record in database. Methods change
and change2
executes transactionally.
@Autowired
private UserRepo userRepo;
@Transactional(isolation = Isolation.SERIALIZABLE)
public void change() {
User user = userRepo.findOne("Jan");
write("before change", user);
sleep(2000);
user.setPassword("new password");
write("after change", user);
}
@Transactional(isolation = Isolation.SERIALIZABLE)
public void change2() {
User user = userRepo.findOne("Jan");
write("before change2", user);
user.setSecondName("new name");
write("after change2", user);
}
and when I call change
and change2
methods I received these logs:
before change User(name=Jan, secondName=Adam, password=Kowalski)
before change2 User(name=Jan, secondName=Adam, password=Kowalski)
after change2 User(name=Jan, secondName=new name, password=Kowalski)
after change User(name=Jan, secondName=Adam, password=new password)
...and after that also I got this exception:
com.mysql.jdbc.exceptions.jdbc4.MySQLTransactionRollbackException: Deadlock found when trying to get lock; try restarting transaction
My question is this: Why does the transaction for change2
start before change
is done? What is the reason of deadlock?