GreenDao 中的交易 [英] Transactions in GreenDao

查看:59
本文介绍了GreenDao 中的交易的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 GreenDao 来存储来自 REST 服务的大量数据.

I'm using GreenDao to store a lot of data, coming from a REST service.

我的很多实体都与关系有关.一切正常,但明天我必须实施一个坚如磐石的工作流程.

A lot of my entities are connected with relations. Everything works great, but tomorrow I have to implement a rocksolid workflow.

当我加载数据时,我必须检查是否发生错误.如果是这样,我必须确保在 SQLite 数据库中没有存储.

When I load my data I have to check if an error occurs. If so, I have to make sure nothing is stored in the SQLite DB.

通常我会处理事务回滚以防万一,否则提交到数据库.

Normally I would work with transactions and rollback in case of an exception, otherwise commit to the db.

现在我只使用 insertordelete 来保存实体,每次我创建一个对象.

For now I just use insertordelete to save an entity, everytime I created an object.

实施的方法是什么?

推荐答案

在插入和更新时 Greendao 检查是否有正在进行的事务.如果是这种情况,greendao 将不会开始新的交易.

On inserts and updates Greendao checks if there is a ongoing transaction. If that is the case greendao will not start a new transaction.

所以唯一要做的就是在您的数据库上启动一个事务,并在您的工作完成或您发现错误后提交/回滚.所有插入和更新都在同一个事务中,这对数据一致性和性能都有好处,因为 greendao 会为每个插入和更新操作启动新事务并提交/回滚.

So the only thing to do is to start a transaction on your database and commit/rollback after your work is done or you notice an error. All inserts and updates will be in the same transaction which has benefits concerning data consistency and also on performance, since greendao will start new transactions with commit/rollback for every insert and update operation.

总结你可以使用这样的代码:

Summarized you can use code like this:

SQLiteDatabase db = dao.getDatabase();
db.beginTransaction();

try {
    // do all your inserts and so on here.
    db.setTransactionSuccessful();
} catch (Exception ex) {
} finally {
    db.endTransaction();
}

我还对我的 greendao 进行了一些调整,以便它不会缓存插入的对象以获得进一步的性能和内存使用优势(因为我一次插入了大量数据,并且我在运行时仅根据用户输入使用很少的数据).请参阅这篇帖子.

I also tweaked my greendao a bit so that it doesn't cache inserted objects to get further performance and memoryusage benefits (since I insert a lot of data once and I only use very few data during runtime depending on user input). See this post.

这篇关于GreenDao 中的交易的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆