在Realm数据库解决方案中,我如何获得性能最佳的最新插入项目?
该代码是我解决问题的解决方案
List<Transactions> allItems = realm.where(Transactions.class).findAll().sort("createdAt", Sort.DESCENDING);
String latestId = allItems.get(0).getId();
getUserLatestTransactions(Integer.parseInt(latestId));
有其他解决方案或Realm已经实现了吗?
以下是您可以做的事情-考虑到Realm读取不需要复制,这意味着它不昂贵,也不会对您的UI线程产生太大影响,在存储项目后,您可以使用findAllSorted("createdAt)
或findAllSorted("id")
,然后使用last()
方法找到最后一个id,如下所示:
//after commitTransaction,
RealmResults<Transactions> allTransactions = realm.where(Transactions.class).findAllSorted("createdAt");
//If you have an incrementing id column, do this
long lastInsertedId = allTransactions.last().getId();
这将为您提供给定模型的最后插入ID。
同样重要的是要提到,为了实现这一点,你必须在你的模型中有一个像这样带有id的列;
public class Transactions extends RealmObject{
@PrimaryKey @Index
private long id;
//getters and setters accordingly!
}
我希望这能有所帮助!祝你好运,编码快乐!
更新
我刚刚意识到realm.copyToRealm(obj)
返回了一个对象!
这意味着你可以简单地做到这一点:
realm.beginTransaction();
Transactions transaction = realm.copyToRealm(newTransaction);
long id = transaction.getId();
realm.commitTransaction();
请试试这个,让我知道!
Transactions item = realm.where(Transactions.class).findAll().last()
注意:如果您只想获得最后一个插入数据,则不需要排序方法
val obj = realm.where<Transactions>()
.sort("createdAt", Sort.DESCENDING)
.findFirst()
if(obj != null){
val latestId = obj.id
}
如果Id是唯一的&增量可以按它进行排序,也可以将时间作为长值,并按照上面的方法进行操作。