3

我有一个Language带有 ForeignCollection 实体的Country实体:

@ForeignCollectionField(eager = false, foreignFieldName = "language")
public ForeignCollection<Country> countries;

我在我的数据库中创建了一个国家,比如说代表法国。后来,我通过查询它的 id 来检索它,我想将它添加到语言的外国国家集合中:

Country country = dbHelper.getCountryDao().queryForId(countryId);
if (country != null) {
    country.language = language;    
    ForeignCollection<Country> countries = language.countries;
    if (countries == null) {
        countries = dbHelper.getLanguageDao().getEmptyForeignCollection("countries");
    }
    countries.add(country); // Illegal state exception thrown here
    language.countries = countries;
    dbHelper.getLanguageDao().create(language);
}

但是,标记的行countries.add(country)会导致抛出非法状态异常:

01-27 13:39:19.112: E/AndroidRuntime(15614): 原因: java.sql.SQLException: 插入数据库失败: INSERT INTO countries( identifier, name, language_id) VALUES (?,?,?) 01-27 13:39 :19.112: E/AndroidRuntime(15614): 在 com.j256.ormlite.misc.SqlExceptionUtil.create(SqlExceptionUtil.java:22)

为什么会.add()触发重新创建存在于数据库和内部 DAO 中的实体?而我应该怎么做呢?

4

2 回答 2

6

为什么 .add() 会触发重新创建存在于数据库和内部 DAO 中的实体?

它这样做是因为它就是这样设计的。引用javadocsEagerForeignCollection#add()

向集合中添加一个元素。这也会将该项目添加到关联的数据库表中。

该国家/地区已存在于表中,因此引发异常。您可以通过执行以下操作将现有国家/地区与语言相关联:

country.language = language;
dbHelper.getCountryDao().update(country);

然后,如果您想用您所做的语言刷新您渴望的收藏:

dbHelper.getLanguageDao().refresh(language); 
于 2013-01-27T16:01:57.967 回答
2

Right now I get an SQL Exception, if I add an already created element to the collection, because of the dao.create() in the add() of the collection realization. But for a quite some time we got a dao.createOrUpdate() method, which is better for this situation because it would do an update or simply nothing if we have an already created entity in collection. Is it possible to change this in the source code?

By the way there is an already done and closed ticket (#31) with changes that should automatically set the parent field value on the collection element. But even in the 4.45 I still have to do this manually. Did I miss something or probably do something wrong?

于 2013-04-01T23:02:31.693 回答