Jfinal中手动提交/回滚 事物

在Jfinal中有个Tx类为事物声明类 在方法或controller上面加@Before({Tx.class})即可,可是这样并不能满足有的业务场景

下面是今天写的手动提交的事物处理方法,希望对大家有用

public  void test(){
        Connection conn=null;
        try
        {
            conn=DbKit.getConfig().getDataSource().getConnection();
            DbKit.getConfig().setThreadLocalConnection(conn);
            conn.setAutoCommit(false);//自动提交变成false
            for(int i=0;i<=3;i++){
                Department d=new Department();
                d.set("DEPID", "department_id.nextval")
                .set("DEPNAME", "测试"+i)
                .set("SUPDEPID", 0)
                .save();

      //if(i>2) System.out.println(1/0); //测试只要其中有一个地方发生异常,就会回滚前面所有事物
            }
            conn.commit();
        }
        catch (Exception e)
        {
            try
            {
                if(null!=conn) conn.rollback();
            }
            catch (SQLException e1)
            {
                e1.printStackTrace();
            }
            throw new ActiveRecordException(e);
        }finally{
            try
            {
                if(null!=conn){
                    conn.close();
                }
            }
            catch (Exception e2)
            {
                e2.printStackTrace();
            }finally{
                DbKit.getConfig().removeThreadLocalConnection();
            }
        }

 

 

//一下是jfinal开发文档中说明处理事物的示例

boolean succeed = Db.tx(new IAtom(){
public boolean run() throws SQLException {
int count = Db.update("update account set cash = cash - ? where id = ?", 100, 123);
int count2 = Db.update("update account set cash = cash + ? where id = ?", 100, 456);
return count == 1 && count2 == 1;
}});

在初始化configInterceptor方法中配置一下是方法名称有事物处理实现

public void configInterceptor(Interceptors me) {
me.add(new TxByRegex(".*save.*"));//正则匹配
me.add(new TxByActionKeys("/cash/trans", "/other"));//访问方法路劲匹配
me.add(new TxByActionMethods("save", "update"));//指定方法名称匹配
}

转载于:https://www.cnblogs.com/laotan/p/4073083.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值