当前位置:Gxlcms > 数据库问题 > JFinal 数据库“手动”事务(提交、回滚)

JFinal 数据库“手动”事务(提交、回滚)

时间:2021-07-01 10:21:17 帮助过:34人阅读

一、用注解 @Before(Tx.class) 实现 事务回滚

@Before(Tx.class)
public void pay() throws Exception {
    //throws exception;
}

  

方法体不能扑捉异常,所有的异常都抛出,当出现异常时事物将回滚(即 事务的回滚 是依赖 抛出异常 来实现的)

优点:简单暴力,不需要去处理每个异常,直接抛出即可;

缺点:不能详细的区分返回数据、视图,只能笼统的报出异常;

 

二、Db.tx(new IAtom(){})

public void pay() {
    final Map<String,String> map = new HashMap<String, String>();
    boolean bl = Db.tx(new IAtom() {
        @Override
        public boolean run() throws SQLException {
             
            if (...) {
                //...
                return false;
            } else {
                ...
                return true;
            }
             
            return true;
        }
    });
     
    this.rendJson(bl, null, map.get("return_words"), null);
}

  

  1. return false 或者 有异常抛出 都会 回滚事务,return true 才会提交事务;
  2. Db.tx 方法是有返回值true/false,可对该 返回值 作为 业务返回;
  3. 如果想让 run() 方法中往外层传递变量,可以在外层定义一个 final 修饰的 容器类的对象 或者 定义map

方法二较方法一更全面,处理更细腻,推荐使用二。

 

注意:方法二可简写(Java8语法)

public void pay() {
    final Map<String,String> map = new HashMap<String, String>();
    boolean bl = Db.tx(() -> {
        if (...) {
            //...
            return false;
        } else {
            ...
            return true;
        }
          
        return true;
    });
      
    this.rendJson(bl, null, map.get("return_words"), null);
}

  

 

JFinal 数据库“手动”事务(提交、回滚)

标签:简单   事物   string   code   this   方法体   全面   get   语法   

人气教程排行