跳到主要内容

事务使用


一、在service实现类中的方法上增加@Transactional注解即可

事务回滚

@Transactional
@Override
public int executeUpdate(MatRepertoryEnter matRepertoryEnter, MatRepertory matRepertory) {
Integer integer = 0, integerm = 0;
matRepertoryEnter.setUuid("09DC9839641D45F6AC06FE2B281229D2");
matRepertoryEnter.setNumber("1");
integer = oaRepertoryEnterMapper.executeUpdate(matRepertoryEnter);
matRepertory.setUuid("8715a07f34084d58b2883140d1cec6aa");
matRepertory.setRnumber("2");
integerm = matRepertoryMapper.executeUpdate(matRepertory);
Integer i = 1 / 0;
return integer == 1 && integerm == 1 ? 1 : 0;
}

二、如果使用try catch事务需手动回滚

try catch事务回滚

    @Transactional
@Override
public int executeUpdate(MatRepertoryEnter matRepertoryEnter, MatRepertory matRepertory) {
Integer integer = 0, integerm = 0;
try {
matRepertoryEnter.setUuid("09DC9839641D45F6AC06FE2B281229D2");
matRepertoryEnter.setNumber("1");
integer = oaRepertoryEnterMapper.executeUpdate(matRepertoryEnter);
matRepertory.setUuid("8715a07f34084d58b2883140d1cec6aa");
matRepertory.setRnumber("2");
integerm = matRepertoryMapper.executeUpdate(matRepertory);
Integer i=1/0;
} catch (Exception e) {
e.printStackTrace();
// 使用 try catch 手动回滚
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
}
return integer == 1 && integerm == 1 ? 1 : 0;
}

三、如果出现不同库情况增加@GlobalTransactional注解即可

@ApiOperation(value = "操作两张表不同库")
@GlobalTransactional
@ResponseBody
@PostMapping(value = "/globalTransactional")
public Object globalTransactional() {
ExampleRightDatagrid exampleRightDatagrid = new ExampleRightDatagrid();
Integer integer = exampleRightDatagridService.insertSelective(getSaveData(exampleRightDatagrid));
log.info("保存1:{}", integer);
ExampleSingleDatagrid exampleSingleDatagrid = new ExampleSingleDatagrid(); //misboot_cloud_vue_zt.example_single_datagrid
Integer integer1 = exampleSingleDatagridService.insertSelective(getSaveData(exampleSingleDatagrid));
log.info("保存2:{}", integer1);
Integer i = 1 / 0;
return success("1");
}