sqliteormliteforeign-collection

Using ForeignCollections in SQLite


I want to write a unit test that basically verifies an object I add to a foreign collection actually gets saved and retrieved correctly when the DAO saves retrieves the object Here is my Entity.

@DatabaseTable
public class Question implements Question, Serializable {

    @DatabaseField
    private String questionText;

    @ForeignCollectionField
    private ForeignCollection<Answer> answers;

    public void addAnswer(Answer answer) {
        answers.add(answer);
    }

What I want to do is create a Question instance add an Answer object to the collection and pass the Question to my DAO which will persist it. The persistence works fine on regular fields so I know there is no problem there.

How do I go about adding an Answer to the collection? When I create the Question it's answers collection is null. Is it what I have to save the new Question and then retrieve it in order for the answers collection to be non null? Or, do I set the answers to a BaseCollection, LazyCollection instance?


Solution

  • This is a FAQ. The right way to do it is to make use of the Dao.getEmptyForeignCollection(...) method to create a collection that you can add items to. Something like:

    Question question = new Question();
    query.answers = questionDao.getEmptyForeignCollection("answers");
    Answer answer1 = new Answer();
    query.answers.add(answer1);
    // this can come before the question.answers.add()
    questionDao.create(question);