ORMLite and adding an existing persisted object to a foreign field collection

I have an object Language

with ForeignCollection of objects Country

:

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

      

I create a country, for example representing France, in my database. Later I retrieve it by requesting its ID and I want to add it to a foreign collection of countries from different countries:

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);
}

      

However, the marked line countries.add(country)

throws an illegal state exception:

01-27 13: 39: 19.112: E / AndroidRuntime (15614): caused by: a java.sql.SQLException: insert into the database failed: the INSERT the INTO countries

( identifier

, name

, language_id

) VALUES 01-27 13 (,,???): 39: 19.112: E / AndroidRuntime (15614): at com.j256.ormlite.misc.SqlExceptionUtil.create (SqlExceptionUtil.java:22)

Why is it .add()

triggering a re-creation of an entity existing in the database and internal DAO? And what should I do instead?

+3


source to share


2 answers


Why does .add () trigger re-creation of entity existing in database and internal DAO?

He does it because that's how it was designed. To quote the javadocs forEagerForeignCollection#add()

:

Add an item to the collection. This will also add the item to the corresponding database table.

The country already exists in the table, so an exception is thrown. You can associate an existing country with a language by doing something like the following:



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

      

Then, if you want to update your favorite collection in the appropriate language:

dbHelper.getLanguageDao().refresh(language); 

      

+6


source


I am currently getting a SQL Exception if I add an already created item to a collection due to dao.create()

in the add()

implementation of the collection. But quite a long time ago we got a method dao.createOrUpdate()

that is better for this situation, because it will do an update or just nothing if we have an already created entity in the collection. Is it possible to change this in the source code?



By the way, the already executed and closed ticket ( # 31 ) with changes that should automatically set the value of the parent field in the collection element. But even at 4.45 I still have to do it manually. Am I missing something or perhaps I did something wrong?

+2


source







All Articles