{"record":{"id":"866ff52b5171e9ac","repo":"hibernate/hibernate-orm","slug":"entity-s-with-identifier-value-s-does-not-ex","errorCode":null,"errorMessage":"Entity `%s` with identifier value `%s` does not exist","messagePattern":"Entity `(.+?)` with identifier value `(.+?)` does not exist","errorType":"exception","errorClass":"FetchNotFoundException","httpStatus":null,"severity":"error","filePath":"hibernate-core/src/main/java/org/hibernate/sql/results/graph/entity/internal/EntityDelayedFetchInitializer.java","lineNumber":162,"sourceCode":"\t\t\tdata.entityIdentifier = identifierAssembler.assemble( rowProcessingState );\n\n\t\t\tif ( data.entityIdentifier == null ) {\n\t\t\t\tdata.setInstance( null );\n\t\t\t\tdata.setState( State.MISSING );\n\t\t\t}\n\t\t\telse {\n\t\t\t\tfinal var entityPersister = getEntityDescriptor();\n\t\t\t\tfinal EntityPersister concreteDescriptor;\n\t\t\t\tif ( discriminatorAssembler != null ) {\n\t\t\t\t\tconcreteDescriptor = determineConcreteEntityDescriptor(\n\t\t\t\t\t\t\trowProcessingState,\n\t\t\t\t\t\t\tdiscriminatorAssembler,\n\t\t\t\t\t\t\tentityPersister\n\t\t\t\t\t);\n\t\t\t\t\tif ( concreteDescriptor == null ) {\n\t\t\t\t\t\t// If we find no discriminator, it means there's no entity in the target table\n\t\t\t\t\t\tif ( !referencedModelPart.isOptional() ) {\n\t\t\t\t\t\t\tthrow new FetchNotFoundException( entityPersister.getEntityName(), data.entityIdentifier );\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdata.setInstance( null );\n\t\t\t\t\t\tdata.setState( State.MISSING );\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tconcreteDescriptor = entityPersister;\n\t\t\t\t}\n\n\t\t\t\tinitialize( data, null, concreteDescriptor );\n\t\t\t}\n\t\t}\n\t}\n\n\tprotected void initialize(\n\t\t\tEntityDelayedFetchInitializerData data,\n\t\t\t@Nullable EntityKey entityKey,","sourceCodeStart":144,"sourceCodeEnd":180,"githubUrl":"https://github.com/hibernate/hibernate-orm/blob/fad1729dce015f908198d57a8d80274a30f905a5/hibernate-core/src/main/java/org/hibernate/sql/results/graph/entity/internal/EntityDelayedFetchInitializer.java#L144-L180","documentation":"EntityDelayedFetchInitializer handles to-one associations resolved 'delayed' (the FK id is read now, the association resolved later from the persistence context or by id). When the row for the target is checked, a null discriminator means no row exists in the target table for that id; if the association is not optional (referencedModelPart.isOptional() == false), Hibernate throws FetchNotFoundException('Entity X with identifier value Y does not exist'). This is the signature of a dangling foreign key: a non-null FK column pointing at an entity that is gone.","triggerScenarios":"A mandatory (optional=false / non-null @ManyToOne or @OneToOne) association whose FK column contains an id with no matching row in the target table; rows deleted while referencing rows kept (FK constraints disabled or absent); target row hidden by @SQLRestriction/@Filter so the discriminator reads as null.","commonSituations":"Manual deletes or bulk cleanup scripts that orphan FKs; databases with FK checking disabled; legacy schemas without FK constraints; environments where another service deletes reference data still referenced by your tables.","solutions":["Repair the data: either restore the missing referenced rows or NULL out / delete the orphaned FK values.","Add and enforce a real FOREIGN KEY constraint so the database rejects dangling references in the first place.","If absence is legitimate, map the association nullable (@ManyToOne(optional=true) with a nullable FK column) or annotate @NotFound(action = NotFoundAction.IGNORE) so Hibernate nulls the association instead of throwing.","Investigate whether @Filter/@SQLRestriction on the target entity hides rows that actually exist."],"exampleFix":"// before\n@ManyToOne(optional = false) // FK points to a deleted Client row\nprivate Client client;\n\n-- fix data + prevent recurrence\nUPDATE invoice SET client_id = NULL WHERE client_id NOT IN (SELECT id FROM client);\nALTER TABLE invoice ADD CONSTRAINT fk_invoice_client FOREIGN KEY (client_id) REFERENCES client (id);\n\n// after (if a missing target is a legal state)\n@ManyToOne\n@NotFound(action = NotFoundAction.IGNORE)\nprivate Client client;","handlingStrategy":"try-catch","validationCode":"// Pre-check for dangling mandatory FKs before running the business query\nString sql = \"select c.id from child c left join parent p on p.id = c.parent_id \"\n           + \"where c.parent_id is not null and p.id is null\";\nList<?> orphans = em.createNativeQuery(sql).getResultList();\nif (!orphans.isEmpty()) throw new IllegalStateException(\"Dangling FKs: \" + orphans);","typeGuard":null,"tryCatchPattern":"try {\n    Order o = em.createQuery(\"select o from Order o join fetch o.client\", Order.class).getSingleResult();\n} catch (FetchNotFoundException e) {\n    // e.getEntityName() / e.getIdentifier() tell you which reference is dangling\n    // handle: alert data team, skip the record, or treat association as absent\n}","preventionTips":["Declare and enforce database FOREIGN KEY constraints for every to-one association.","Run a periodic anti-join integrity job for tables whose FKs cannot be constrained.","Decide explicitly per association: mandatory (optional=false) or tolerant (@NotFound(IGNORE)); never rely on luck.","Keep deletes and inserts in one transaction so orphans cannot be committed."],"tags":["hibernate","orm","many-to-one","dangling-foreign-key","entity-not-found","data-integrity"],"backgroundTag":"dangling-foreign-key","analyzedSha":"fad1729dce015f908198d57a8d80274a30f905a5","analyzedAt":"2026-08-22T04:13:57.527Z","schemaVersion":2},"datasetVersion":"2026-08-22T09:17:25.309Z"}