您的位置:首页 > 移动开发 > Android开发

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

2016-03-03 21:58 357 查看
OrmLite提供了批处理的方法

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


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

假设有下列实体Person,对应下表头。
IdLastNameFirstNameAddressCity
插入速度比较
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语句执行效率的大幅度提高,但执行的过程中如果出问题,这次批处理所有的插入数据会被回滚清除。 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  orm Android sql sqlite