ClassCastException: org.hibernate.internal.SessionImpl cannot be cast to org.hibernate.ejb.HibernateEntityManager in Hibernate

Solution Verified - Updated

Environment

  • Red Hat JBoss Enterprise Application Platform (EAP) 7.2
  • Hibernate 5.3

Issue

  • Attempting to unwrap the Hibernate EntityManager instance in order to obtain the encapsulated legacy interface object (the Hibernate Session):

    org.hibernate.Session session = entityManager.unwrap(org.hibernate.ejb.HibernateEntityManager.class).getSession();
    
  • Encountering an exception:

    java.lang.ClassCastException: org.hibernate.internal.SessionImpl cannot be cast to org.hibernate.ejb.HibernateEntityManager
    

Resolution

This issue1 is resolved in This content is not included.EAP 7.2 cumulative patch (CP) 1 and later releases. Production systems should use the latest available cumulative patch. However, the entity manager can now be directly unwrapped as a session (the preferred approach):

org.hibernate.Session session = entityManager.unwrap(org.hibernate.Session.class);

Root Cause

This is a known defect (Content from hibernate.atlassian.net is not included.HHH-13281).

Components
Category

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.