【发布时间】:2013-05-25 12:08:50
【问题描述】:
用嵌入的外部集合持久化对象的正确方法是什么?目前我正在使用以下内容,但如果我在 zonePlay 已经存在时向客户 zonePlays 集合添加“zoneplay”对象,则会收到错误Could not create data element in dao。我应该使用某种 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);
【问题讨论】:
标签: ormlite foreign-collection