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

时间:2015-07-21 10:14:54

标签: java android ormlite

我确保几次阅读有关此主题的文档,但我似乎无法理解它。我有一个名为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模型后,我能够得到如下内容:

主页

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

现在,我不想更新persons模型中Person字段的内容。我只想更新Home对象的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);

不幸的是,这个问题让我不知道如何更新外国收藏的字段。

我做错了什么?

1 个答案:

答案 0 :(得分:0)

好的,所以今天我实际吃了一些食物,这可能与我能解决这个问题的原因有直接关系。吃早餐后,今天早上的文件更有意义,事实证明我做错了。由于PersonHome的外来集合,它正在维护一个映射回父节点的外键...所以我对外来集合进行了更新,而不是VOILA!

而不是这样做:

 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.

另外,我必须修改我的childs属性的注释,该注释指定了我的父模型的外键并添加了columnName = "home_id"

希望这有意义,并在将来帮助任何人。