【问题标题】:How to deal with OrmLite ForeignCollection Fields in Android with GSON models如何使用 GSON 模型处理 Android 中的 OrmLite ForeignCollection 字段
【发布时间】:2012-09-09 21:50:44
【问题描述】:

所以,我有几个 OrmLite 4.41 模型类,它们最初由 GSON 填充(为清晰起见进行了简化)

public class Crag {
  @DatabaseField(id=true) private int id;
  @ForeignCollectionField(eager=true, maxEagerLevel=2) @SerializedName("CragLocations")
  private Collection<CragLocation> cragLocations;
}

public class CragLocation {
    @DatabaseField(id=true) private int id;
    @DatabaseField private int locationType;
    @DatabaseField(foreign=true, foreignAutoCreate=true, foreignAutoRefresh=true)
    private Crag crag;  
    @DatabaseField(foreign=true, foreignAutoCreate=true, foreignAutoRefresh=true)
    private Location location;
}

public class Location {
    @DatabaseField(id=true) private int id;
    @DatabaseField private BigDecimal latitude;
    @DatabaseField private BigDecimal longitude;
}

然后我正在测试事情是否按我预期的那样发生......

@Test
public void canFindById() {
    Crag expected = ObjectMother.getCrag431();
    _repo.createOrUpdate(template431);
    Crag actual = _repo.getCragById(431);
    assertThat(actual, equalTo(template431));
}

他们不相等...为什么不呢?因为在 GSON(ObjectMother.getCrag431())创建的对象中,Crag 的 cragLocations 字段是一个 ArrayList,而在 OrmLite 加载的对象中,它是一个 EagerForeignCollection

我在这里错过了一个技巧吗?有没有办法告诉 OrmLite 我希望 Collection 是什么类型?我是否应该有一个方法将集合作为数组列表返回并测试其是否相等?

提前致谢

【问题讨论】:

    标签: android ormlite foreign-collection


    【解决方案1】:

    有没有办法告诉 OrmLite 我希望 Collection 是什么类型?

    没有办法做到这一点。当你的 Crag 被 ORMLite 返回时,它要么是 EagerForeignCollection 要么是 LazyForeignCollection。

    我是否应该只使用一个将集合作为数组列表返回并测试其相等性的方法?

    我假设在您的Crag.equals(...) 方法中,您正在测试cragLocations 字段是否等于this.cragLocations.equals(other.cragLocations)。这是行不通的,因为正如您所猜测的,它们是不同的类型。

    如果您需要测试相等性,您可以将它们都提取为一个数组。比如:

    Array.equals(
        this.cragLocations.toArray(new CragLocation[this.cragLocations.size()]),
        other.cragLocations.toArray(new CragLocation[this.cragLocations.size()]));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多