【问题标题】:Trouble understanding/using the ForeignCollectionField in ORMLite无法理解/使用 ORMLite 中的 ForeignCollectionField
【发布时间】: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


    【解决方案1】:

    用嵌入的外部集合持久化对象的正确方法是什么?

    “正确”的方法可能是使用它自己的 DAO 添加元素——而不是通过外部集合。这样就可以使用createOrUpdate(...) 方法:

      Dao<ZonePlay, Integer> zoneDao = DatabaseHelper.getInstance(ctx).getZoneDao();
      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;
            zoneDao.createOrUpdate(zp);
      }
    

    如果我在 zonePlay 已存在的情况下向客户 zonePlays 集合添加“zoneplay”对象,则会出现错误,无法在 dao 中创建数据元素。

    没错。如果您尝试将ZonePlay 添加到Customer 的外部集合中,这将尝试添加到表中。如果表中已经存在ZonePlay,那么这将引发异常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-22
      • 2019-03-30
      相关资源
      最近更新 更多