{"record":{"id":"634e298ec01527be","repo":"hibernate/hibernate-orm","slug":"illegal-attempt-to-associate-a-managedentity-with","errorCode":null,"errorMessage":"Illegal attempt to associate a ManagedEntity with two open persistence contexts: {}","messagePattern":"Illegal attempt to associate a ManagedEntity with two open persistence contexts: (.+?)","errorType":"exception","errorClass":"HibernateException","httpStatus":null,"severity":"error","filePath":"hibernate-core/src/main/java/org/hibernate/engine/internal/EntityEntryContext.java","lineNumber":214,"sourceCode":"\t}\n\n\tprivate void putImmutableManagedEntity(ManagedEntity managed, int instanceId, ImmutableManagedEntityHolder holder) {\n\t\tif ( immutableManagedEntityXref == null ) {\n\t\t\timmutableManagedEntityXref = new InstanceIdentityStore<>();\n\t\t}\n\t\timmutableManagedEntityXref.put( managed, instanceId, holder );\n\t}\n\n\tprivate void checkNotAssociatedWithOtherPersistenceContextIfMutable(ManagedEntity managedEntity) {\n\t\t// we only have to check mutable managedEntity\n\t\tfinal var entityEntry = (EntityEntryImpl) managedEntity.$$_hibernate_getEntityEntry();\n\t\tif ( entityEntry != null && entityEntry.getPersister().isMutable() ) {\n\t\t\tfinal var entryPersistenceContext = entityEntry.getPersistenceContext();\n\t\t\tif ( entryPersistenceContext != null && entryPersistenceContext != persistenceContext ) {\n\t\t\t\tif ( entryPersistenceContext.getSession().isOpen() ) {\n\t\t\t\t\t// NOTE: otherPersistenceContext may be operating on the entityEntry in a different thread.\n\t\t\t\t\t//       it is not safe to associate entityEntry with this EntityEntryContext.\n\t\t\t\t\tthrow new HibernateException(\n\t\t\t\t\t\t\t\"Illegal attempt to associate a ManagedEntity with two open persistence contexts: \" + entityEntry\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t// otherPersistenceContext is associated with a closed PersistenceContext\n\t\t\t\t\tCORE_LOGGER.stalePersistenceContextInEntityEntry( entityEntry.toString() );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Does this entity exist in this context, associated with an {@link EntityEntry}?\n\t *\n\t * @param entity The entity to check\n\t *\n\t * @return {@code true} if it is associated with this context\n\t */","sourceCodeStart":196,"sourceCodeEnd":232,"githubUrl":"https://github.com/hibernate/hibernate-orm/blob/fad1729dce015f908198d57a8d80274a30f905a5/hibernate-core/src/main/java/org/hibernate/engine/internal/EntityEntryContext.java#L196-L232","documentation":"For bytecode-enhanced entities (ManagedEntity), Hibernate stores the EntityEntry inside the entity itself. When such an entity - already carrying an EntityEntry whose persistence context is a DIFFERENT, still-open session - is added to this EntityEntryContext, and the entity's persister is mutable, Hibernate throws: the other session (possibly another thread) may still be using that injected entry, so associating it here would corrupt both sessions. A closed other context is tolerated with a stale-entry log.","triggerScenarios":"Loading a bytecode-enhanced entity in session A, then while A is still open passing that same instance to session B (merge/lock/refresh/saveOrUpdate/reference) so B tries to attach it; also concurrent use of one entity across threads/sessions. The check only fires for mutable persisters - immutable entities can float between contexts.","commonSituations":"Build-time or runtime bytecode enhancement enabled (lazy-loading/dirty-tracking instrumentation) plus code that reuses detached-ish entities in a new open session; long-lived entities cached in application memory and fed into request sessions; async processing where the originating session stays open on another thread; test suites leaking sessions per class.","solutions":["Close (or clear) the first session before handing the entity to another session - with the origin context closed, Hibernate logs a stale entry and proceeds.","Use merge() semantics on a detached COPY rather than re-associating the same enhanced instance into a second open session.","Do not cache enhanced entities across requests; cache DTOs or ids and reload per session.","Ensure one thread/session 'owns' an entity at a time; never operate the same enhanced instance from two open sessions concurrently."],"exampleFix":"// before - enhanced entity attached to two open sessions\ntry (Session a = sf.openSession()) { orderA = a.find(Order.class, id); }\n// session a still open elsewhere; then:\ntry (Session b = sf.openSession()) {\n    b.lock(orderA, LockMode.NONE);   // Illegal attempt ...\n}\n// after - close the first session, or merge a copy\ntry (Session b = sf.openSession()) {\n    Order managed = b.merge(orderA); // detached copy gets its own entry\n}","handlingStrategy":"validation","validationCode":"// Guard: before attaching an enhanced entity to a new session, check its current entry\nstatic boolean isAttachedToOpenSession(Object entity) {\n    if (entity instanceof org.hibernate.engine.spi.ManagedEntity me) {\n        var entry = me.$$_hibernate_getEntityEntry();\n        return entry != null\n            && entry.getPersistenceContext() != null\n            && entry.getPersistenceContext().getSession().isOpen();\n    }\n    return false;\n}\n// if (isAttachedToOpenSession(order)) order = newSession.merge(order);","typeGuard":"static boolean isManagedEntity(Object o) {\n    return o instanceof org.hibernate.engine.spi.ManagedEntity;\n}","tryCatchPattern":"catch (HibernateException e) {\n    if (e.getMessage() != null && e.getMessage().startsWith(\"Illegal attempt to associate a ManagedEntity\")) {\n        // close/clear the original session, or merge a copy instead of re-associating\n        target = session.merge(detachedCopy);\n    } else throw e;\n}","preventionTips":["Scope enhanced entities to one open session; close or clear the origin session before cross-session use.","Pass detached copies or ids between layers instead of live enhanced instances.","Never touch the same enhanced entity from two open sessions on different threads."],"tags":["bytecode-enhancement","managed-entity","persistence-context","detached-entity","session"],"backgroundTag":"entity-two-open-sessions","analyzedSha":"fad1729dce015f908198d57a8d80274a30f905a5","analyzedAt":"2026-08-22T04:13:57.527Z","schemaVersion":2},"datasetVersion":"2026-08-22T09:17:25.309Z"}