非WEB环境下使用ActiveRecord 事务学习笔记

本文介绍了一个使用JFinal框架进行数据库操作的例子,包括通过ActiveRecord进行数据保存及查询的操作方式,并展示了如何利用Db工具类执行数据库事务。
public class ActiveRecordTest {

    public static void main(String[] args) {
        DruidPlugin dp = new DruidPlugin("jdbc:mysql://localhost/jfinal", "root", "");
        ActiveRecordPlugin arp = new ActiveRecordPlugin(dp);
        //arp.addMapping("blog", Blog.class);
        // 与web环境唯一的不同是要手动调用一次相关插件的start()方法
        dp.start();
        arp.start();
        // 通过上面简单的几行代码,即可立即开始使用
        new Blog().set("title", "title").set("content", "cxt text").save();
        Blog.me.findById(123);
    }

}

事务测试

        boolean success  = Db.tx(new IAtom() {
            public boolean run() throws SQLException {
                int count2 = Db.update("update account set cash = cash + ? where id = ?", 100, 2);
                int count1 = Db.update("update account set cash = cash - ? where id = ?", 100, 1);
                return count1==1&&count2==1;
            }
        });
        System.out.println(success);

注解配置

    @Before(Tx.class)
    public void txtxtx(){
        int count2 = Db.update("update account set cash = cash + ? where id = ?", 100, 2);
        int count1 = Db.update("update account set cash = cash - ? where id = ?", 100, 1);

    }

在主函数中调用

        ActiveRecordTest activeRecordTest = Enhancer.enhance(ActiveRecordTest.class);
        activeRecordTest.txtxtx();

必须使用Enhancer.enhance或Duang.duang,否则注解是无效的

 

转载于:https://my.oschina.net/zhuqianli/blog/823126

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值