4

I have two class:

public class Questionnaire {

    @DatabaseField(generatedId=true, useGetSet=true)
    private Long id;

    @DatabaseField
    private int type;

    @DatabaseField
    private String title;

    @DatabaseField
    private String description;


    @ForeignCollectionField(eager = true)   
    private Collection<Question> questions; 
// Get and Set omitted

and

  public class Question {

        @DatabaseField(generatedId=true, useGetSet=true)
        private Long id;

        @DatabaseField
        private int type;

        @DatabaseField
        private String description;


        @DatabaseField(foreign = true, foreignAutoRefresh= true)
        private Questionnaire questionario;
//get and set ommited

When I save a Questionnaire with a List of Questions. The objects are persisted, but I lose the relationship.

I save in this way:

ForeignCollection<Question> questions =
    getDao(Questionnaire.class).getEmptyForeignCollection("questions");

for(Question question : DataUtil.getAllQuestions()) {
    questions.add(question);
}

Questionnaire questionnarie = new Questionnaire();
questionnarie.setQuestions(questions);
questionnarie.setTitle("Normal");
questionnarie.setDescription("Questionário normal");
getDao(Questionnaire.class).createOrUpdate(questionarie);

When I retrieved this register from database, a Question data doesn't have a reference for Questionnaire, and my Questionnaire doesn't have question list filled.

Any help will be appreciated.

Gray
  • 115,027
  • 24
  • 293
  • 354
leonvian
  • 4,719
  • 2
  • 26
  • 31

1 Answers1

17

The problem is that you are not setting the questionario field on your Question objects. The relationship is from the Question to the associated Questionnaire. There is nothing in the Questionnaire table that points the other way. See the documentation on foreign objects.

I would recommend doing something like the following:

Dao<Questionnaire, Long> dao = getDao(Questionnaire.class);
ForeignCollection<Question> questions =
    dao.getEmptyForeignCollection("questions");

Questionnaire questionnarie = new Questionnaire();
questionnarie.setQuestions(questions);
questionnarie.setTitle("Normal");
questionnarie.setDescription("Questionário normal");
dao.createOrUpdate(questionarie);

for(Question question : DataUtil.getAllQuestions()) {
    // you must set the questionnarie field on the Question
    // if it is a generated-id, it must be set _after_ it has been created
    question.setQuestionnaire(questionnarie);
    questions.add(question);
}
Gray
  • 115,027
  • 24
  • 293
  • 354
  • 1
    If my Question have another collection reference like a Collection of Option and Option have another collection. I Have to do the same steps I did to save Questionnaire? Is there a better way to save a Collection? – leonvian Nov 01 '12 at 03:30
  • Worked like a charm !Thanks Gray and OP – moujib Sep 10 '14 at 15:06