避免嵌套事务

时间:2018-04-26 12:48:41

标签: java spring-boot transactional propagation

以下是我方法的结构:

    @Override
    @Transactional
    public methodOuter(){
      //some processing
      methodInner1();
      methodInner2();
    }

    @Override
    @Transactional
    public methodInner1(){
    //save something to db
    }

    @Override
    @Transactional
    public methodInner2(){
    //some processing
    //throws exception
    }

方案methodInner1()已成功处理,但methodInner2()抛出异常。所以我想在methodInner1()中回滚提交。目前methodInner1()中的提交未被回滚。我希望methodOuter()成为单一交易

1 个答案:

答案 0 :(得分:2)

如果您知道抛出异常的类型(假设它是NPE),您可以尝试类似

NotificationCenter.default.addObserver(self, selector: #selector(orientationChanged), name:  Notification.Name("UIDeviceOrientationDidChangeNotification"), object: nil)

@objc func orientationChanged() {

if(UIDeviceOrientationIsLandscape(UIDevice.current.orientation)){

    print("landscape")
}

if(UIDeviceOrientationIsPortrait(UIDevice.current.orientation)){

    print("Portrait")
}

在这种情况下,您不需要注释"内部"功能。如果抛出NullPointerException,则会回滚methodOuter。如果要为每个可能的异常进行回滚,则应将注释更改为

public ActionResult Test(string inputString = "stack")
{
    try
    {
        int carrots = int.Parse(inputString);
        return Json(new { Data = carrots }, JsonRequestBehavior.AllowGet);
    }
    catch (Exception)
    {
        return new HttpStatusCodeResult(400);
    }
}

顺便说一句:RuntimeExceptions将导致回滚,无论它们是否被注释。