使用 ForeignCollections 更新和刷新实体时出现 ORMLite 问题

ORMLite issues when updating and refreshing entities with ForeignCollections

我一定要阅读几次关于这个主题的文档,但我似乎无法理解它。我有一个名为 Home 的模型,它的 ForeignCollectionPerson

Home.class:

public class Home implements Serializable{

     @DatabaseField(id = true, canBeNull = false, columnName = "id")
     private long id;

     @ForeignCollectionField(eager = true, maxEagerLevel = 2)
     private Collection<Person> persons = new ArrayList<>();

     //constructors, getters, and setters...
}

Person.class:

public class Person {
     @DatabaseField(id=true, canBeNull = false, columnName = "id")
     private long id;

     @DatabaseField(foreign = true, foreignAutoCreate = true, foreignAutoRefresh = true)
     private Home home;
     //constructors getters setters and other properties that are not important for this question
}

现在,在最初将值插入我的 HomePerson 模型后,我能够得到如下所示的内容:

首页Object:

{
     "id" : 1, 
     "persons" : [{"id" : 1}, {"id" : 2}, {"id" : 3}]
}

现在我不想从 Person 模型更新 persons 字段的内容。我只想更新 Home object 的 persons 字段。

我尝试了以下方法:

home.setPersons(newArrayOfPersons); //this array is the same array except I removed one element.
homeDao.update(home);

上面的代码没有抛出任何错误,但它似乎没有更新我的 SQLite 数据库。

然后我尝试使用 UpdateBuilder:

 UpdateBuilder<Home, Long> updateBuilder = homeDao.updateBuilder();
 updateBuilder.where().eq("id", home.getId());
 updateBuilder.updateColumnValue("persons", newArrayOfPersons);
 updateBuilder.update();
 homeDao.refresh(home);

不幸的是,这个问题抛出了我无法更新外国字段的异常 Collection。

我做错了什么?

好吧,我今天确实吃了点东西,这可能与我能够解决这个问题的原因有直接关系。今天早上吃过早饭后,文档变得更有意义了,结果证明我做错了。由于 PersonHome 的外部集合,它维护着一个映射回 parent 的外键...所以我对外部集合进行了更新,瞧!

而不是这样做:

 UpdateBuilder<Home, Long> updateBuilder = homeDao.updateBuilder();
 updateBuilder.where().eq("id", home.getId());
 updateBuilder.updateColumnValue("persons", newArrayOfPersons);
 updateBuilder.update();
 homeDao.refresh(home);

我这样做了:

UpdateBuilder<Person, Long> updateBuilder = personDao.updateBuilder();
updateBuilder.where().in("id", arrayOfIdsOfPersons); //I just got all the ids of each object I want to update
updateBuilder.updateColumnValue("home_id", secondHome); //changed the mapping to point to another `Home Object`
updateBuilder.update();

homeDao.refresh(secondHome); //not sure if I need this one though.

此外,我不得不修改我的子属性的注释,该注释指定了我的 parents 模型的外键并添加了 columnName = "home_id"

希望这是有道理的,对以后的任何人都有帮助。