{"record":{"id":"115340f5b19c65fd","repo":"hibernate/hibernate-orm","slug":"given-entity-is-not-associated-with-the-persistenc-115340","errorCode":null,"errorMessage":"Given entity is not associated with the persistence context","messagePattern":"Given entity is not associated with the persistence context","errorType":"exception","errorClass":"IllegalArgumentException","httpStatus":null,"severity":"error","filePath":"hibernate-core/src/main/java/org/hibernate/event/internal/DefaultDeleteEventListener.java","lineNumber":95,"sourceCode":"\t}\n\n\tprivate boolean optimizeUnloadedDelete(@Nonnull DeleteEvent event) {\n\t\tfinal Object object = event.getObject();\n\t\tfinal var lazyInitializer = extractLazyInitializer( object );\n\t\tif ( lazyInitializer != null && lazyInitializer.isUninitialized() ) {\n\t\t\tfinal var source = event.getSession();\n\t\t\tfinal var factory = event.getFactory();\n\t\t\tfinal var persister =\n\t\t\t\t\tfactory.getMappingMetamodel()\n\t\t\t\t\t\t\t.findEntityDescriptor( lazyInitializer.getEntityName() );\n\t\t\tfinal Object id = lazyInitializer.getInternalIdentifier();\n\t\t\tfinal var key = source.generateEntityKey( id, persister );\n\t\t\tfinal var persistenceContext = source.getPersistenceContextInternal();\n\t\t\tfinal var entityHolder = persistenceContext.getEntityHolder( key );\n\t\t\tif ( ( entityHolder == null || entityHolder.getEntity() == null || !entityHolder.isInitialized() )\n\t\t\t\t\t&& canBeDeletedWithoutLoading( source, persister ) ) {\n\t\t\t\tif ( factory.getSessionFactoryOptions().isJpaBootstrap() && entityHolder == null ) {\n\t\t\t\t\tthrow new IllegalArgumentException( \"Given entity is not associated with the persistence context\" );\n\t\t\t\t}\n\t\t\t\t// optimization for deleting certain entities without loading them\n\t\t\t\tpersistenceContext.reassociateProxy( object, id );\n\t\t\t\tif ( !persistenceContext.containsDeletedUnloadedEntityKey( key ) ) {\n\t\t\t\t\tpersistenceContext.registerDeletedUnloadedEntityKey( key );\n\t\t\t\t\tif ( persister.hasOwnedCollections() ) {\n\t\t\t\t\t\t// we're deleting an unloaded proxy with collections\n\t\t\t\t\t\tfor ( var type : persister.getPropertyTypes() ) { //TODO: when we enable this for subclasses use getSubclassPropertyTypeClosure()\n\t\t\t\t\t\t\tdeleteOwnedCollections( type, id, source );\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tsource.getActionQueue().addAction( new EntityDeleteAction( id, persister, source ) );\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}","sourceCodeStart":77,"sourceCodeEnd":113,"githubUrl":"https://github.com/hibernate/hibernate-orm/blob/fad1729dce015f908198d57a8d80274a30f905a5/hibernate-core/src/main/java/org/hibernate/event/internal/DefaultDeleteEventListener.java#L77-L113","documentation":"DefaultDeleteEventListener can delete certain lazy proxies/unloaded entities without loading them, but under JPA bootstrap (EntityManagerFactory-built factory) it must enforce the JPA rule that remove() targets a managed entity. When the delete target's EntityKey is not present in the persistence context at all, it throws IllegalArgumentException('Given entity is not associated with the persistence context').","triggerScenarios":"em.remove(detachedEntity) where the entity was detached via em.detach()/clear() or created in another EntityManager; em.remove(em.getReference(X.class, id)) after the context was cleared; removing a proxy whose target was never loaded and whose key was evicted from the context.","commonSituations":"Two-EntityManager flows (load in one, remove in another); long conversation patterns where entities detach between operations; code migrating from native Session.delete() (which tolerated detached instances) to JPA remove().","solutions":["Reattach first: em.remove(em.merge(entity))","Or load then delete inside the same context: em.remove(em.find(X.class, id))","For bulk deletion by key, use a JPQL DELETE query instead of entity removal","Do not mix entity instances across EntityManager lifecycles"],"exampleFix":"// before\nem.remove(detachedCustomer); // IllegalArgumentException\n\n// after\nem.remove(em.merge(detachedCustomer));","handlingStrategy":"validation","validationCode":"if (!em.contains(entity)) {\n    entity = em.merge(entity); // reattach so remove() sees a managed entity\n}\nem.remove(entity);","typeGuard":"static <T> T managedOrMerged(EntityManager em, T entity) {\n    return em.contains(entity) ? entity : em.merge(entity);\n}","tryCatchPattern":null,"preventionTips":["Only call remove() on entities managed by the same EntityManager","After em.clear()/detach(), merge before remove","Use JPQL delete-by-id for bulk deletions","Do not reuse entities across EntityManager lifecycles"],"tags":["delete","detached-entities","persistence-context","jpa"],"backgroundTag":"detached-entity-operation","analyzedSha":"fad1729dce015f908198d57a8d80274a30f905a5","analyzedAt":"2026-08-22T04:13:57.527Z","schemaVersion":2},"datasetVersion":"2026-08-22T09:17:25.309Z"}