Adding, removing objects from ForeignCollection

I have an object that contains a ForeignCollection with a getter and setter for the collection

public class TextQuestion{ @ForeignCollectionField private ForeignCollection<TextAnswer> answers; .... 

I have a Servicer wrapper class that encapsulates a DAO

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

My question is How to add, remove items from this collection through the Wrapper class of service? Higher is my effort, but I just got completely lost, threw collections into lists, etc. The problem is that when I want to add an answer to ForeignCollection questions, there would be no problem if the collection of answers was not zero, but I want to collect the question up, add answers to it before saving it. From the previous question, I understand that I need to call getEmptyForeignCollection if the parent has not been retrieved from the database. Should there be an easy way to do this? Any such example that worked would be nice.

+4
source share
1 answer

The problem is that when I want to add an answer to the ForeignCollection questions, there would be no problem if the collection of answers was not null, but I want to build Question up,

I think you are close. You must be able to:

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

answers may also be Collection<TextAnswer> , but this is not a List .

+6
source

All Articles