@Transactional 注解作用
时间: 2023-11-21 13:57:02 浏览: 93
Spring @Transactional注解失效解决方案
5星 · 资源好评率100%
@Transactional注解是Spring框架中用于管理事务的注解。它可以作用于接口、类、类方法,并且可以配置多个属性信息。当放在类上时,表示该类的所有public方法都使用相同的事务属性信息;当放在方法上时,表示该方法使用自己的事务属性信息,会覆盖类的事务配置信息。@Transactional注解的属性包括propagation、isolation、timeout、readOnly、rollbackFor、noRollbackFor等。其中,propagation属性用于指定事务的传播行为,isolation属性用于指定事务的隔离级别,timeout属性用于指定事务的超时时间,readOnly属性用于指定事务是否只读,rollbackFor属性用于指定哪些异常需要回滚事务,noRollbackFor属性用于指定哪些异常不需要回滚事务。
示例代码如下:
```java
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, readOnly = false, timeout = 36000, rollbackFor = Exception.class)
public void addUser(User user) {
userDao.addUser(user);
}
@Override
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, readOnly = false, timeout = 36000, rollbackFor = Exception.class)
public void updateUser(User user) {
userDao.updateUser(user);
}
@Override
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, readOnly = false, timeout = 36000, rollbackFor = Exception.class)
public void deleteUser(int userId) {
userDao.deleteUser(userId);
}
@Override
@Transactional(propagation = Propagation.SUPPORTS, isolation = Isolation.DEFAULT, readOnly = true, timeout = 36000, rollbackFor = Exception.class)
public User getUserById(int userId) {
return userDao.getUserById(userId);
}
@Override
@Transactional(propagation = Propagation.SUPPORTS, isolation = Isolation.DEFAULT, readOnly = true, timeout = 36000, rollbackFor = Exception.class)
public List<User> getAllUsers() {
return userDao.getAllUsers();
}
}
```
阅读全文