因此,我有一些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成为哪种类型?我是否应该有一个将集合作为数组列表返回并测试是否相等的方法?

提前致谢

最佳答案

有没有办法告诉OrmLite我希望该Collection成为哪种类型?


没有办法做到这一点。当您的Crag由ORMLite返回时,它将是EagerForeignCollectionLazyForeignCollection


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


我假设在您的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()]));

关于android - 如何使用GSON模型处理Android中的OrmLite ForeignCollection字段,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12343293/

10-12 04:30