我正在使用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....
}
Run Code Online (Sandbox Code Playgroud)
问题是,我想更新一些领域的ç或插入新ç在B的RealmList.我应该以什么顺序这样做以保持关系?谁能举一个真实的例子?此外,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;
}
}
Run Code Online (Sandbox Code Playgroud)
示例-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();
Run Code Online (Sandbox Code Playgroud)
示例-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();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9262 次 |
| 最近记录: |