{"record":{"id":"eceb9714e92f710c","repo":"flowable/flowable-engine","slug":"error-while-flushing-entitymanager","errorCode":null,"errorMessage":"Error while flushing EntityManager: ","messagePattern":"Error while flushing EntityManager: ","errorType":"exception","errorClass":"FlowableException","httpStatus":null,"severity":"error","filePath":"modules/flowable-variable-service/src/main/java/org/flowable/variable/service/impl/types/EntityManagerSessionImpl.java","lineNumber":60,"sourceCode":"    }\n\n    public EntityManagerSessionImpl(EntityManagerFactory entityManagerFactory, boolean handleTransactions, boolean closeEntityManager) {\n        this.entityManagerFactory = entityManagerFactory;\n        this.handleTransactions = handleTransactions;\n        this.closeEntityManager = closeEntityManager;\n    }\n\n    @Override\n    public void flush() {\n        if (entityManager != null && (!handleTransactions || isTransactionActive())) {\n            try {\n                entityManager.flush();\n            } catch (IllegalStateException ise) {\n                throw new FlowableException(\"Error while flushing EntityManager, illegal state\", ise);\n            } catch (TransactionRequiredException tre) {\n                throw new FlowableException(\"Cannot flush EntityManager, an active transaction is required\", tre);\n            } catch (PersistenceException pe) {\n                throw new FlowableException(\"Error while flushing EntityManager: \" + pe.getMessage(), pe);\n            }\n        }\n    }\n\n    protected boolean isTransactionActive() {\n        if (handleTransactions && entityManager.getTransaction() != null) {\n            return entityManager.getTransaction().isActive();\n        }\n        return false;\n    }\n\n    @Override\n    public void close() {\n        if (closeEntityManager && entityManager != null && entityManager.isOpen()) {\n            try {\n                entityManager.close();\n            } catch (IllegalStateException ise) {\n                throw new FlowableException(\"Error while closing EntityManager, may have already been closed or it is container-managed\", ise);","sourceCodeStart":42,"sourceCodeEnd":78,"githubUrl":"https://github.com/flowable/flowable-engine/blob/d6d39ce1c69ff244f2d9dc6af756a9b95e865586/modules/flowable-variable-service/src/main/java/org/flowable/variable/service/impl/types/EntityManagerSessionImpl.java#L42-L78","documentation":"Flowable's EntityManagerSessionImpl wraps a JPA EntityManager used to persist JPA-typed variables. When the session flushes at the end of a command and the underlying JPA provider throws a PersistenceException (any persistence-layer failure not covered by the more specific IllegalStateException/TransactionRequiredException handlers), it is rethrown wrapped in this FlowableException with the original message appended.","triggerScenarios":"Calling FlowableException-producing operations (e.g. setting/reading JPA variables via VariableService) when entityManager.flush() throws a PersistenceException: constraint violations, optimistic-lock failures, SQL errors, or mapping problems detected at flush time.","commonSituations":"Entity violates a DB unique/foreign-key constraint; JPA entity mapping mismatch with the schema; optimistic locking @Version conflict; underlying datasource down; flush occurs inside a Flowable command whose JPA entity state became inconsistent.","solutions":["Inspect the cause chain (FlowableException#getCause) for the real PersistenceException and the JPA provider's constraint/violation details","Fix the entity state that fails flush: resolve constraint violations, duplicate keys, or null mandatory columns","Verify the JPA entity mappings match the actual database schema","Confirm the datasource/DB is reachable and healthy","Ensure flush happens within an active transaction (Flowable command context provides one)"],"exampleFix":"// before\ntry {\n    variableScope.setVariable(\"customer\", detachedEntity);\n} catch (FlowableException e) {\n    log.error(e.getMessage()); // message is generic\n}\n// after\ntry {\n    variableScope.setVariable(\"customer\", managedOrValidEntity);\n} catch (FlowableException e) {\n    log.error(\"JPA flush failed\", e.getCause()); // log root PersistenceException\n    throw new BusinessException(\"Invalid customer entity: \" + e.getCause().getMessage());\n}","handlingStrategy":"try-catch","validationCode":"// validate entity before setVariable\nif (entity == null) throw new IllegalArgumentException(\"entity required\");\n// e.g. constraint pre-checks, required fields\nObjects.requireNonNull(entity.getId(), \"id must be set before persisting as variable\");","typeGuard":"boolean isFlushSafe(Object e) { return e != null && e.getClass().isAnnotationPresent(jakarta.persistence.Entity.class); }","tryCatchPattern":"try { runtimeService.setVariable(executionId, \"customer\", entity); } catch (FlowableException e) { Throwable root = e.getCause(); log.error(\"JPA flush failed: {}\", root != null ? root.getMessage() : e.getMessage(), root); throw new BusinessException(\"Entity failed to persist\", e); }","preventionTips":["Always log/inspect FlowableException.getCause() — the real JPA failure is in the cause chain","Validate entity constraints (uniques, required fields) before storing as variable","Keep DB schema and entity mappings in sync (schema validation in tests)","Ensure entities are managed/persisted before flush at variable write time"],"tags":["jpa","flush","database","flowable"],"backgroundTag":"database-write-failed","analyzedSha":"d6d39ce1c69ff244f2d9dc6af756a9b95e865586","analyzedAt":"2026-09-11T06:41:19.413Z","contentChangedAt":"2026-09-11T06:41:19.413Z","schemaVersion":2},"datasetVersion":"2026-09-14T11:17:12.474Z"}