使用嵌入式外部集合持久化对象的正确方法是什么?目前我正在使用以下内容,但Could not create data element in dao
如果我在 zonePlay 已经存在的情况下将“zoneplay”对象添加到客户 zonePlays 集合中,则会出现错误。是否应该使用某种 upsert 方法添加到外部集合中,或者我是否需要在插入之前以某种方式检查是否存在?
@DatabaseTable
public class Customer {
@DatabaseField(id = true)
public int id;
@ForeignCollectionField(eager = true)
public ForeignCollection<ZonePlay> zonePlays;
@DatabaseField
public String email;
public Customer(String json) {
final JSONArray zonesJson = customerJson.getJSONArray("zoneplays");
this.zonePlays = DatabaseHelper.getInstance(ctx).getCustomerDao().getEmptyForeignCollection("zonePlays");
for (int i = 0; i < numZones; i++) {
final JSONObject rawZone = zonesJson.getJSONObject(i);
ZonePlay zp = new ZonePlay();
zp.id = rawZone.getInt("id");
zp.score = rawZone.getInt("score");
zp.Customer = this;
this.zonePlays.add(zp);
}
}
@DatabaseTable
public class ZonePlay {
@DatabaseField(id = true)
public int id;
@DatabaseField(foreign=true)
public Customer customer;
}
然后我运行这个
Customer cust = new Customer(client.response);
DatabaseHelper db = DatabaseHelper.getInstance(getApplicationContext());
db.getDao(Customer.class).createOrUpdate(cust);