android - 插入或更新的 Realm 顺序

标签 android realm

我正在使用 Realm 来为 Android 项目保留对象。 问题是我有许多类和内部字段作为类和它们的列表的组合。 有点像

class A extends RealmObject{
   @PrimaryKey long id;
   B b;
} 

class B extends RealmObject{
   @PrimaryKey long id;
   RealmList<C> cList;
}

class C extends RealmObject{
  @PrimaryKey long id;
  Date date;
  String value;
  //other fields....
}

问题是我想更新C的一些字段或者在B的RealmList中插入新的C。为了保持关系,我应该按什么顺序这样做?谁能举个真实的例子?此外,Realm 不支持 ID 的自动递增,目前我在启动时将它们设置为 currentTimeInMillis。有更好的替代方案吗?

最佳答案

让你的模型类成为

class A extends RealmObject{
   @PrimaryKey
   private long id;
   private B b;

   public A(){
       //required empty constructor
   }

   public A(long id){
       this.id = id;
   }

   public B getB(){
       return b;
   }

   public void setB(B b){
       this.b = b;
   }
} 

class B extends RealmObject{
   @PrimaryKey
   private long id;
   private RealmList<C> cList = new RealmList<>();

   public B(){
       //required empty constructor
   }

   public B(long id){
   this.id = id;
   }

   public RealmList<C> getCList(){
       return cList;
   }

   public void setCList(RealmList<C> cList){
       this.cList = cList;
   }
}

class C extends RealmObject{
  @PrimaryKey 
  private long id;
  private Date date;
  private String value;
  //other fields....

  public C(){
      //required empty constructor
  }

  public C(long id){
      this.id = id;
  }
}

示例 - 1:创建新对象并根据层次分配它

    Realm realm = Realm.getDefaultInstance();
    realm.beginTransaction();

    C c = new C(id);
    realm.insertOrUpdate(c);

    B b = new B(id);
    RealmList<C> list = b.getcList();
    list.add(c);
    realm.insertOrUpdate(b);

    A a = new A(id);
    a.setB(b);
    realm.insertOrUpdate(a);
    realm.commitTransaction();

示例 - 2:更新数据库中的现有条目

    C c = realm.where(C.class).equalTo("id", id).findFirst();
    realm.beginTransaction();
    c.setValue("New Value"); //setter method for value
    c.insertOrUpdate();
    //while updating the existing entry in the database, you need not worry about the hierarchy, Realm will maintain the same hierarchy for updates
    //If you want to copy the existing entry from one object to another, you can use combination of method-1 and method-2
    realm.commitTransaction();

关于android - 插入或更新的 Realm 顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41953956/

相关文章:

android - 将 Firebase 与 Kotlin 协程一起使用

Swift Realm 检索数据

android - 如何将 copyToRealmOrUpdate 用于列表?

java - 特殊字符问题

android - IBM MobileFirst 7 依赖项

java - 我总是收到此错误 "unknow param 0x00008824 glUtilsParamSize: unknow param 0x0000882"

c# - 在 Realm 中使用特定于项目的 ViewModel 的最佳方式是什么?

javascript - Realm React-Native : Access same realm from JS(react native code) and android(java)

android - 在 Realm 表中选择一个随机行

python - REST/JSON/XML-RPC/SOAP