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语句执行效率的大幅度提高,但执行的过程中如果出问题,这次批处理所有的插入数据会被回滚清除。