SpringBoot使用事务
程序员文章站
2022-07-07 10:40:04
...
SpringBoot使用事务
- 使用@Transactional注解来进行事务控制
- 使用controller测试
/**
* @Description
* @Author
* @Version V1.0.0
* @Since 1.0
* @Date 2019-09-25
*/
@Api(value = "test", description = "测试样例文档")
@RestController
@RequestMapping("/test")
@Slf4j
@Validated
public class TransactionalController {
@Autowired
private UserService userService;
@ApiOperation(value = "注解式事务测试", httpMethod = "GET")
@GetMapping("alluser")
public String transationalTest(){
List<User> users = userService.selectAll();
User u1 = new User();
u1.setUsername("张小飞");
userService.insertSelective(u1);
return "index";
}
}
- 逻辑实现类
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
//测试只读事务
@Override
@Transactional(readOnly = true)
public List<User> selectAll() {
List<User> list = userMapper.selectAll();
list.stream().forEach(user -> System.out.println (user.getUsername()));
//readOnly = true 查询的读一致性,sql执行到数据返回期间不允许更改数据
//如果放开下面的插入逻辑将报错
// User u1 = new User();
// u1.setUsername("张小飞");
// userMapper.insertSelective(u1);
List<User> list2 = userMapper.selectAll();
list2.stream().forEach(user -> System.out.println (user.getUsername()));
return list;
}
/**
* //测试事务超时
* Spring事务超时 = 事务开始时到最后一个Statement创建时时间 + 最后一个Statement的执行时超时时间(即其queryTimeout)。所以在在执行Statement之外的超时无法进行事务回滚。
* @param record
* @return
*/
@Override
@Transactional(timeout = 3, rollbackFor = Exception.class,isolation = Isolation.DEFAULT)
//timeout单位是毫秒,指定引起事务回滚的异常,隔离级别,Mysql默认REPEATATABLE_READ(若A方法调用B方法,A事务读了一条记录,B事务将不允许修改这条记录)
public int insertSelective(User record) {
int num = userMapper.insertSelective(record);
try {
Thread.sleep(1000);//单位是毫秒
} catch (InterruptedException e) {
e.printStackTrace();
}
userMapper.selectAll();
if(num > 0){
System.out.println ("插入"+ num + "条记录" );
}
return num;
}
}