{"record":{"id":"9b2b1b8d889562db","repo":"hibernate/hibernate-orm","slug":"cannot-set-field-to-instantiate","errorCode":null,"errorMessage":"Cannot set field '{}' to instantiate '{}'","messagePattern":"Cannot set field '(.+?)' to instantiate '(.+?)'","errorType":"exception","errorClass":"InstantiationException","httpStatus":null,"severity":"error","filePath":"hibernate-core/src/main/java/org/hibernate/sql/results/graph/instantiation/internal/DynamicInstantiationAssemblerInjectionImpl.java","lineNumber":75,"sourceCode":"\t\tfinal var argType = argument.getAssembledJavaType().getJavaTypeClass();\n\t\tfinal String alias = argument.getAlias();\n\n\t\t// see if we can find a property with the given name...\n\t\tfor ( var propertyDescriptor : beanInfo.getPropertyDescriptors() ) {\n\t\t\tif ( propertyMatches( alias, argType, propertyDescriptor ) ) {\n\t\t\t\tfinal var setter = propertyDescriptor.getWriteMethod();\n\t\t\t\tsetter.setAccessible(true);\n\t\t\t\treturn new BeanInjection( new BeanInjectorSetter<>( setter ), argument );\n\t\t\t}\n\t\t}\n\n\t\t// see if we can find a Field with the given name...\n\t\tfinal var field = findField( targetJavaType, alias, argType );\n\t\tif ( field != null ) {\n\t\t\treturn new BeanInjection( new BeanInjectorField<>( field ), argument );\n\t\t}\n\t\telse {\n\t\t\tthrow new InstantiationException(\n\t\t\t\t\t\"Cannot set field '\" + alias + \"' to instantiate '\" + targetJavaType.getName() + \"'\"\n\t\t\t);\n\t\t}\n\t}\n\n\t@Override\n\tpublic JavaType<T> getAssembledJavaType() {\n\t\treturn target;\n\t}\n\n\t@Override\n\t@SuppressWarnings(\"unchecked\")\n\tpublic T assemble(RowProcessingState rowProcessingState) {\n\t\tfinal T result;\n\t\ttry {\n\t\t\tfinal var constructor = target.getJavaTypeClass().getDeclaredConstructor();\n\t\t\tconstructor.setAccessible( true );\n\t\t\tresult = constructor.newInstance();","sourceCodeStart":57,"sourceCodeEnd":93,"githubUrl":"https://github.com/hibernate/hibernate-orm/blob/fad1729dce015f908198d57a8d80274a30f905a5/hibernate-core/src/main/java/org/hibernate/sql/results/graph/instantiation/internal/DynamicInstantiationAssemblerInjectionImpl.java#L57-L93","documentation":"For injection-style dynamic instantiation (select new with a no-arg-constructible target), DynamicInstantiationAssemblerInjectionImpl.injection() tries, per argument, first a matching JavaBean property (name plus compatible type via propertyMatches) and then a field with the alias name and compatible type (findField). If neither exists for an argument's alias, it throws InstantiationException(\"Cannot set field '<alias>' to instantiate '<target class>'\") at query-plan build time: the query aliases do not line up with any setter or field on the target.","triggerScenarios":"`select new com.acme.Dto(o.name as nm, o.age as yrs) ...` where Dto has no setNm/nm field and no setYrs/yrs field; alias matches a property but the argument type is incompatible, so the property check fails AND no same-named field with the right type exists (type compatibility is part of matching); typos or casing mismatches between alias and property name.","commonSituations":"Renaming DTO properties or query aliases independently; adding a new select item with an alias the DTO never got; alias/property type drift after model changes (e.g. property changed from int to String so propertyMatches no longer accepts); query and DTO updated in different commits.","solutions":["Make every select-item alias match, by name and type, a setter (or field) on the target class - exact spelling and an assignable type.","Add the missing property (field plus setter) with the aliased name, or rename the alias in the query to the existing property.","If types cannot match, switch to a constructor expression with an explicit constructor for full control.","Cover every dynamic-instantiation query with a startup smoke test (createQuery plus execution on test data) so the failure is caught at build time, not production."],"exampleFix":"// before\npublic class EmpDto { private String fullName; /* no 'nm' */ }\nem.createQuery(\"select new com.acme.EmpDto(e.name as nm) from Employee e\", EmpDto.class);\n// -> Cannot set field 'nm' to instantiate 'com.acme.EmpDto'\n\n// after\nem.createQuery(\"select new com.acme.EmpDto(e.name as fullName) from Employee e\", EmpDto.class);","handlingStrategy":"validation","validationCode":"// At startup, verify every query alias has a matching, type-compatible setter or field\nSet<String> props = new HashSet<>();\nfor (PropertyDescriptor pd : Introspector.getBeanInfo(EmpDto.class).getPropertyDescriptors())\n    if (pd.getWriteMethod() != null) props.add(pd.getName());\nfor (Field f : EmpDto.class.getDeclaredFields()) props.add(f.getName());\nfor (String alias : List.of(\"fullName\" /* aliases used in the query */)) {\n    if (!props.contains(alias))\n        throw new IllegalStateException(\"alias '\" + alias + \"' has no setter/field on EmpDto\");\n}","typeGuard":"// Reflective guard: alias must resolve to an injectable member\nstatic boolean aliasInjectable(Class<?> dto, String alias, Class<?> assembled) {\n    try {\n        for (PropertyDescriptor pd : Introspector.getBeanInfo(dto).getPropertyDescriptors())\n            if (pd.getName().equals(alias) && pd.getWriteMethod() != null\n                    && pd.getWriteMethod().getParameterTypes()[0].isAssignableFrom(assembled))\n                return true;\n        return dto.getDeclaredField(alias).getType().isAssignableFrom(assembled);\n    } catch (IntrospectionException | NoSuchFieldException e) { return false; }\n}","tryCatchPattern":"try {\n    rows = q.getResultList();\n} catch (org.hibernate.query.sqm.sql.internal.InstantiationException e) {\n    if (String.valueOf(e.getMessage()).startsWith(\"Cannot set field '\")) {\n        // the message names the bad alias and target class: add the property or fix the alias\n    }\n}","preventionTips":["Keep query aliases and DTO property names identical - one vocabulary, maintained together.","Build a startup check that validates aliases against the DTO for every projection query.","Change aliases and DTO fields in one commit; grep for the alias string project-wide."],"tags":["hibernate","orm","dynamic-instantiation","alias-mismatch","bean-injection","dto","query-projection"],"backgroundTag":"dynamic-instantiation-alias-mismatch","analyzedSha":"fad1729dce015f908198d57a8d80274a30f905a5","analyzedAt":"2026-08-22T04:13:57.527Z","schemaVersion":2},"datasetVersion":"2026-08-22T09:17:25.309Z"}