Hi there,
I am using Hibernate via JPA, in other words EntityManager. I have written a custom validator annotation that checks a OneToMany relationship for the size of the Set:
Code:
...
public class AssertOptionsValidator implements Validator<AssertOptions>,
PropertyConstraint {
@Override
public void initialize(AssertOptions arg0) {}
@SuppressWarnings("unchecked")
@Override
public boolean isValid(Object arg0) {
if (!(arg0 instanceof Set)) return false;
Set<Option> options = (Set<Option>) arg0;
if (options.size() < 2) return false;
int correctCount = 0;
Iterator iter = options.iterator();
while (iter.hasNext()) {
Option option = (Option) iter.next();
if (option.isCorrect()) correctCount++;
}
return (correctCount == 1);
}
@Override
public void apply(Property arg0) {}
}
My model is something like this:
Quiz-<Question-<Option
Where a quiz has many questions and a question has many options. If I create the relevant objects and call em.persist(quiz) from within a transactional context, eg:
Code:
...
@Repository
@Transactional
public class QuizDaoImpl extends AbstractBaseDao implements QuizDao {
protected EntityManager em;
@PersistenceContext
public void setEntityManager(EntityManager em) {
this.em = em;
}
@Override
public void addQuiz(Quiz quiz) {
em.persist(quiz);
}
@Override
public void updateQuiz(Quiz quiz) {
em.merge(quiz);
}
}
Everything works fine. However, if I create the quiz, persist that, then add questions and options to the quiz after the initial transaction, then attempt to merge it, the arg passed to validator.isValid has a zero length, even though I have added Options to the Question:
Code:
...
Quiz quiz = new Quiz();
quizDao.addQuiz(quiz);
Question question = new Question();
question.addOption(new Option());
question.addOption(new Option());
quiz.addQuestion(question);
quizDao.updateQuiz(quiz);
I've checked in the debugger and the length of the Set is clearly zero even though I have added Options to Question.
I have set all relevant OneToMany mappings to CascadeType=ALL. All of the fetchTypes for those mappings are eager.
Does anyone have any idea why the validator should work for persisting a new Quiz object but should fail for merging an existing Quiz object with new Questions and Options?
Thanks a lot,
Matt