2016-08-14 60 views
4

在Realm数据库解决方案中,如何获得最新插入项目的最佳性能?Java Realm获取最新插入项目

这段代码是我的解决方案,以解决

List<Transactions> allItems = realm.where(Transactions.class).findAll().sort("createdAt", Sort.DESCENDING); 
String    latestId = allItems.get(0).getId(); 
getUserLatestTransactions(Integer.parseInt(latestId)); 

有没有其他的解决方案或领域具有实现的?

+1

我学会了在字符串中隐藏整数的难题,这是一个糟糕的主意!使用多久 – Eenvincible

回答

8

这里是你能做什么 - 考虑境界读作无份,这意味着它不贵,也不会影响你的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! 
} 

我希望这有助于!祝你好运,快乐的编码!

UPDATE

我刚刚意识到realm.copyToRealm(obj)返回一个对象!

这意味着你可以简单地这样做:

realm.beginTransaction(); 
Transactions transaction = realm.copyToRealm(newTransaction); 
long id = transaction.getId(); 
realm.commitTransaction(); 

请试试这个,让我知道!

+0

谢谢先生,没有任何其他解决方案来获取,而不是所有的数据到列表?像使用mysql解决方案'last_insert_id()'是? –

+0

我目前还没有看到任何其他的解决方案,但我会继续搜索,如果我找到一个将会更新你; – Eenvincible

+0

然后我投票你的帖子,谢谢:) –

0

如果Id是唯一的&递增,你可以按它排序或把时间作为长的价值,并做与上面的一样,它应该工作。