微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

android – createOrUpdate()始终使用ORMLite在数据库中创建一个新条目

在我的 Android项目中,Ormlite用作缓存.我正在从Web服务器下载数据并将其放入数据库.我在我的对象上调用createOrUpdate,但数据库中出现重复的对象.数据库条目是相同的,除了主键(这只是一个自动递增的整数).我认为,由于我的第二个对象还没有一个主键,Ormlite认为这两个对象是不同的,即使每个其他的字段是相同的.

有人知道这是否是真的?

解决方法

您不应该调用createOrUpdate,除非您的对象已经设置了一个id字段. Ormlite确定它是否存在于数据库中的方式是在其上执行查询.代码
ID id = extractId(data);
// assume we need to create it if there is no id  <<<<<<<<<<<<<<<<<<<<<<<
if (id == null || !idExists(id)) {
    int numRows = create(data);
    return new CreateOrUpdateStatus(true,false,numRows);
} else {
    int numRows = update(data);
    return new CreateOrUpdateStatus(false,true,numRows);
}

我将扩大javadocs来解释这个更好.他们在那里很弱.抱歉.我已经将它们更新为:

This is a convenience method for creating an item in the database if it does not exist. The id is extracted from the data argument and a query-by-id is made on the database. If a row in the database with the same id exists then all of the columns in the database will be updated from the fields in the data parameter. If the id is null (or 0 or some other default value) or doesn’t exist in the database then the object will be created in the database. This also means that your data item must have an id field defined.

原文地址:https://www.jb51.cc/android/311638.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐