讓你的模型類是
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:在DB更新現有條目
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();
'realm.copyToRealmOrUpdate(一);'可以與插件來代替,更快 –
感謝@TimCastelijns不知道這一點,只是閱讀文檔,看起來多少更高效。更新了答案。 –
我既不,EpicPandaForce前段時間告訴我:) –