Problems saving Collection using ORMLite on Android

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-06 06:09:03

问题


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.


回答1:


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);
}


来源:https://stackoverflow.com/questions/12885499/problems-saving-collection-using-ormlite-on-android

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!