2015-07-21 109 views
0

我确保几次阅读有关此主题的文档,但似乎无法将其包围。我有一个名为Home的模型,其ForeignCollectionPerson使用ForeignCollections更新和刷新实体时发生ORMLite问题

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模型,我能有什么,看起来像这样:

Home对象

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

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

不幸的是,这一次把我约我怎么能不更新的字段是国外收藏例外。

我在做什么错?

回答

0

好吧,我今天吃了一些食物,可能与我为什么能解决这个问题有直接关系。早餐后,文档更有意义,事实证明我做的都是错的。由于PersonHome的外部集合,因此它保留一个映射回父级的外键......所以我对Foreign集合进行了更新,而对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. 

此外,我不得不改变我的孩子的属性,这些属性指定的外键注解我的父母模型,并添加了columnName = "home_id"

希望t他是有道理的,并在未来帮助任何人。