Android中使用OrmLite(三):批处理

OrmLite提供了批处理的方法

mDao.callBatchTasks(new Callable<Object>() {
    @Override
    public Object call() throws Exception {
        return null;
    }
});

此方法提供了批量执行操作功能,提高了执行速度,同时如果中间发生错误,数据库将回滚。

假设有下列实体Person,对应下表头。
Id LastName FirstName Address City

插入速度比较
Person person;
long start = SystemClock.currentThreadTimeMillis();
Log.i("OrmLiteDao", "start common time : " + start);
for (int i = 0; i < 10000; i++) {
    person = new Person("lastName", "firstName", "chaoyang", "Beijing");
    try {
        mDao.create(person);
    } catch (SQLException e) {
        e.printStackTrace();
    }
}
long end = SystemClock.currentThreadTimeMillis();
Log.i("OrmLiteDao", "common time : " + (end - start));

start = SystemClock.currentThreadTimeMillis();
Log.i("OrmLiteDao", "start batch time : " + start);

try {
    mDao.callBatchTasks(new Callable<Object>() {
        Person person;

        @Override
        public Object call() throws Exception {
            for (int i = 0; i < 10000; i++) {
                person = new Person("lastName", "firstName", "chaoyang", "Beijing");
                try {
                    mDao.create(person);
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }
    });
} catch (Exception e) {
    e.printStackTrace();
}
end = SystemClock.currentThreadTimeMillis();
Log.i("OrmLiteDao", "batch task time : " + (end - start));

执行结果:
03-03 21:41:13.985 6052-6052/com.yuntao.testormlite I/OrmLiteDao: start common time : 206
03-03 21:42:30.819 6052-6052/com.yuntao.testormlite I/OrmLiteDao: common time : 29858
03-03 21:42:30.819 6052-6052/com.yuntao.testormlite I/OrmLiteDao: start batch time : 30064
03-03 21:42:33.737 6052-6052/com.yuntao.testormlite I/OrmLiteDao: batch task time : 2227

普通插入速度5列,10000行,花费时间29秒多
批处理中插入同样数据,花费2秒多,插入速度比普通快了一个数量级。

插入异常处理

try {
    mDao.callBatchTasks(new Callable<Object>() {
        @Override
        public Object call() throws Exception {
            for (int i = 0; i < 100; i++) {
                if (i == 50) {
                    throw new Exception();
                }
            }
            return null;
        }
    });
} catch (Exception e) {
    e.printStackTrace();
}

执行之后,发现表中数据是没有变化的。
当插入出错,数据库将回滚。

原理:
关系型数据库事物必须具备ACID的特性,即原子性(Atomicity)、一致性(Consistency)、隔离性(Isolation)、持久性(Durability)。“auto-commit”模式表示每条SQL语句执行完毕后把它作出的修改立刻提交给数据库并使之永久化,事实上,这相当于把每一条语句都隐含地当做一个事务来执行。这样保证了数据库的ACID,但付出的代价就是降低SQL语句的执行效率。开启批任务处理之后,OrmLite关闭了数据库的“auto-commit”模式,在全部语句执行完之后才提交一次,因此带来SQL语句执行效率的大幅度提高,但执行的过程中如果出问题,这次批处理所有的插入数据会被回滚清除。 
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值