MySQL中的事务是一组一起执行或都不执行的SQL语句。事务的主要目的是保证数据的一致性和完整性。MySQL默认情况下是自动提交模式,即每条SQL语句都会立即执行并提交。为了手动控制事务,可以使用注解(在Spring框架中)或直接使用SQL语句来开启、提交或回滚事务。
MySQL支持两种事务隔离级别:
事务常用于以下场景:
在Spring框架中,可以使用@Transactional注解来开启事务。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
@Transactional
public void transferMoney(int fromId, int toId, double amount) {
// 扣款操作
User fromUser = userRepository.findById(fromId).orElseThrow(() -> new RuntimeException("User not found"));
fromUser.setBalance(fromUser.getBalance() - amount);
userRepository.save(fromUser);
// 充值操作
User toUser = userRepository.findById(toId).orElseThrow(() -> new RuntimeException("User not found"));
toUser.setBalance(toUser.getBalance() + amount);
userRepository.save(toUser);
}
}原因:
@Transactional注解只能用于public方法。解决方法:
rollbackFor属性指定需要回滚的异常类型。@Transactional(rollbackFor = Exception.class)
public void transferMoney(int fromId, int toId, double amount) throws Exception {
// ...
}原因:
不同的隔离级别可能导致脏读、不可重复读或幻读等问题。
解决方法:
根据业务需求选择合适的隔离级别。
@Transactional(isolation = Isolation.REPEATABLE_READ)
public void transferMoney(int fromId, int toId, double amount) {
// ...
}通过以上信息,您可以更好地理解MySQL事务的概念、优势、类型和应用场景,并解决常见的问题。