我有两节课:
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
和
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
当我用问题列表保存问卷时。对象是持久的,但我失去了关系。
我以这种方式保存:
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);
当我从数据库中检索此注册时,Question
数据没有Questionnaire
的引用,而我的Questionnaire
没有填写问题列表。
任何帮助将不胜感激。
答案 0 :(得分:17)
问题是您没有在questionario
个对象上设置Question
字段。关系是从Question
到关联的Questionnaire
。 Questionnaire
表中没有任何内容指向另一种方式。请参阅documentation on foreign objects。
我建议做以下事情:
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);
}