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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With