在Android上使用ORMLite保存集合的问题

时间:2012-10-14 19:00:57

标签: android ormlite

我有两节课:

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没有填写问题列表。

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:17)

问题是您没有在questionario个对象上设置Question字段。关系是从Question到关联的QuestionnaireQuestionnaire表中没有任何内容指向另一种方式。请参阅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);
}