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.

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...