zoukankan      html  css  js  c++  java
  • 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"));//指定方法名称匹配
    }

  • 相关阅读:
    jQuery 工具函数
    cdh 5.13 centos6.9安装
    centos 6.9 NTP基准时间服务器配置
    cloudera cdh5.13.0 vmware 快速安装
    centos 7.3+nginx+jira(.bin)+mysql
    zabbix 3.2.6+centos 7 +nginx 1.12+ mysql 5.6+ Grafana +php 5.6
    centos 6.9 +nginx 配置GIT HTTPS服务器(证书采用自签名)
    好难啊 姿态解算 算是解决了
    stm32 iic读取mpu6050失败 改用串口
    stm32 延时函数 delay_ms 范围
  • 原文地址:https://www.cnblogs.com/laotan/p/4073083.html
Copyright © 2011-2022 走看看