【问题标题】:Adding, removing objects from a ForeignCollection从 ForeignCollection 添加、删除对象
【发布时间】:2012-07-18 11:15:12
【问题描述】:

我有一个包含 ForeignCollection 的实体,该实体带有用于 Collection 的 getter 和 setter

public class TextQuestion{

    @ForeignCollectionField
    private ForeignCollection<TextAnswer> answers;
    ....

我有一个封装了 DAO 的 Servicer 包装类

public class TextQuestionService
{

    private static TextQuestionService instance;
    private static Dao<TextQuestion, Integer> textQuestionDAO;
    private static DatabaseHelper dbHelper = new DatabaseHelper();


    public void addAnswer( TextQuestion textQuestion, TextAnswer answer )
    {
        List<Answer> answers = (List)textQuestion.getAnswers();
        if( answers == null )
        {
            try
            {
                answers = (List)textQuestionDAO.getEmptyForeignCollection("answers");
            } catch (SQLException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        answers.add(answer);
    }

我的问题是 如何通过 Wrapper 服务类从该集合中添加、删除项目? 以上是我的努力,但我刚刚完全迷失了,将集合转换为列表等。 问题是,当我想向 Questions ForeignCollection 添加一个 Answer 时,如果 Answers Collection 不为 null 但我想构建 Question,则在持久化之前向其添加 Answers 不会有问题。从上一个问题中,我了解到如果尚未从数据库中检索到父级,我需要调用 getEmptyForeignCollection。必须有一个简单的方法来做到这一点?任何类似的例子都会很好

【问题讨论】:

    标签: android ormlite foreign-collection


    【解决方案1】:

    问题是当我想向 Questions ForeignCollection 添加一个 Answer 时,如果 Answers Collection 不为 null 但我想构建 Question 就没有问题,

    我认为你很接近。你应该能够做到:

    ForeignCollection<TextAnswer> answers = textQuestion.getAnswers();
    if (answers == null) {
        answers = textQuestionDAO.getEmptyForeignCollection("answers");
    }
    answers.add(answer);
    

    answers 也可以是Collection&lt;TextAnswer&gt;,但不是List。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多