I have an entity that contains a ForeignCollection with a getter & 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 do I add, remove items from this collection via the Wrapper service class? Above is my effort but I have just got completely lost, casting Collections to Lists etc. The problem is when I want to add an Answer to the Questions ForeignCollection there would be no problem if the Answers Collection was not null but I want to build the Question up, add Answers to it before persisting it. From a previous question I understand I need to call the getEmptyForeignCollection if the parent has not been retrieved from the DB. There must be a simple way to do this? Any worked similar example would be nice
The problem is when I want to add an Answer to the Questions ForeignCollection there would be no problem if the Answers Collection was not null but I want to build the Question up,
I think you are close. You should be able to do:
ForeignCollection<TextAnswer> answers = textQuestion.getAnswers();
if (answers == null) {
answers = textQuestionDAO.getEmptyForeignCollection("answers");
}
answers.add(answer);
answers
can also be a Collection<TextAnswer>
but it is not a List
.