ForeignCollection create or update

548 Views Asked by At

How do I create OR update a ForeignCollection in OrmLite?

If I try to simply add an object to a ForeignCollection, the add method acts as a create (insert into) method, but if the object already exists I will get an error about not having a unique primary key. I don't want duplicates to appear with autoincrementing primary keys, so this is fine to get this notice.

If I use the update method, then it will error if there is nothing to update.

It seems that the foreigncollection object doesn't have a way to tell me if an object is already existing in the database.

So is the only way to write a separate query myself, see if each object exists and drop the ones that have changed?

1

There are 1 best solutions below

2
Eliott Roynette On

If you are using for example :

@DatabaseTable(tableName = "question")
public class QuestionDb implements Serializable {

    @ForeignCollectionField(foreignFieldName = "question", eager = true)
    private ForeignCollection<AnswerDb> answers;
}

@DatabaseTable(tableName="answers")
public class AnswerDb implements Serializable{

    @DatabaseField (foreign=true,canBeNull=true,columnName=FIELD_QUESTIONID)
    private QuestionDb question;
}

You will have to use the function createOrUpdate of the AnswersDB.

answerYouWantToAdd.setQuestion(yourQuestion);
answerDao.createOrUpdate(answerYouWantToAdd);