ClassCastException when changing a collection association to a set if @PreUpdate listener exists in Hibernate
Environment
- Red Hat JBoss Enterprise Application Platform (EAP) 7
- Hibernate 5
Issue
-
An association is defined between two entities and a
PreUpdatelistener is usedpublic class EmployeeListener { @PreUpdate void onPreUpdate(Object o) { } } @Entity @EntityListeners( EmployeeListener.class ) public class Employee { ... @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY) protected Collection<Task> tasks; ... } @Entity public class Task { ... } -
Though the association is defined to use collection/bag semantics, it is being assigned a set
HashSet<Task> tasks = new HashSet<Task>(); tasks.add(new Task("Some work")); employee.setTasks(tasks); entityManager.merge(employee); entityManager.flush(); -
A
ClassCastExceptionis raised during flush after the update of the associationjava.lang.ClassCastException: java.util.HashSet cannot be cast to org.hibernate.collection.spi.PersistentCollection at org.hibernate.event.internal.FlushVisitor.processCollection(FlushVisitor.java:43) at org.hibernate.event.internal.AbstractVisitor.processValue(AbstractVisitor.java:104) at org.hibernate.event.internal.AbstractVisitor.processValue(AbstractVisitor.java:65) at org.hibernate.event.internal.AbstractVisitor.processEntityPropertyValues(AbstractVisitor.java:59) at org.hibernate.event.internal.DefaultFlushEntityEventListener.onFlushEntity(DefaultFlushEntityEventListener.java:166) at org.hibernate.event.internal.AbstractFlushingEventListener.flushEntities(AbstractFlushingEventListener.java:235) at org.hibernate.event.internal.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:94) at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:38) at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1483) at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1469)
Resolution
This issue1 is resolved in This content is not included.EAP 7.2 cumulative patch (CP) 4 and later releases. Production systems should use the latest available cumulative patch.
Root Cause
This is a known defect (Content from hibernate.atlassian.net is not included.HHH-13466).
This solution is part of Red Hat’s fast-track publication program, providing a huge library of solutions that Red Hat engineers have created while supporting our customers. To give you the knowledge you need the instant it becomes available, these articles may be presented in a raw and unedited form.