@Transactional注解使用样例
时间: 2023-11-08 12:02:17 浏览: 140
@Transactional注解在Spring中用于管理事务。下面是一些使用@Transactional注解的场景样例:
1. 场景一:在方法上使用@Transactional注解,使事务正常起作用。当方法执行没有异常时,事务会正常提交;当方法执行出现异常时,数据会回滚。
代码示例:
```
@Service
public class ComeServiceImpl implements ComeService {
@Autowired UserMapper userMapper;
@Override
@Transactional
public int saveUser() {
User user1 = new User(11,"a",111,"a");
userMapper.saveUser(user1);
// int i = 1 / 0;
User user2 = new User(11,"b",111,"b");
userMapper.saveUser(user2);
return 0;
}
}
```
2. 场景二:在类的方法上使用@Transactional注解,指定事务的传播行为(Propagation)和隔离级别(Isolation)。
代码示例:
```
@Service
public class ComeServiceImpl implements ComeService {
@Autowired UserMapper userMapper;
@Override
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT)
public int saveUser() {
// ...
}
}
```
3. 场景三:在类的方法上使用@Transactional注解,指定事务的只读属性(readOnly)。
代码示例:
```
@Service
public class ComeServiceImpl implements ComeService {
@Autowired UserMapper userMapper;
@Override
@Transactional(readOnly = true)
public User getUser(int id) {
return userMapper.getUser(id);
}
}
```
4. 场景四:在类的方法上使用@Transactional注解,指定事务的超时时间(timeout)。
代码示例:
```
@Service
public class ComeServiceImpl implements ComeService {
@Autowired UserMapper userMapper;
@Override
@Transactional(timeout = 10)
public int saveUser() {
// ...
}
}
```
5. 场景五:同一个Service内方法调用,当@Transactional注解作用在B方法上时,事务不起作用。即使A方法使用了@Transactional注解,B方法内部的事务不会被管理。
代码示例:
```
@Service
@Slf4j
public class ComeServiceImpl implements ComeService {
@Autowired UserMapper userMapper;
@Override
@Transactional
public int A() {
User user1 = new User(11,"a",111,"a");
userMapper.saveUser(user1);
this.B();
return 0;
}
@Override
public int B() {
User user2 = new User(11,"b",111,"b");
userMapper.saveUser(user2);
int i = 1 / 0;
return 0;
}
}
```
阅读全文