{"record":{"id":"d7df49c5a972ff3c","repo":"hibernate/hibernate-orm","slug":"error-instantiating-class","errorCode":null,"errorMessage":"Error instantiating class '{}'","messagePattern":"Error instantiating class '(.+?)'","errorType":"exception","errorClass":"InstantiationException","httpStatus":null,"severity":"error","filePath":"hibernate-core/src/main/java/org/hibernate/sql/results/graph/instantiation/internal/DynamicInstantiationAssemblerConstructorImpl.java","lineNumber":52,"sourceCode":"\n\t@Override\n\tpublic JavaType<R> getAssembledJavaType() {\n\t\treturn resultType;\n\t}\n\n\t@Override\n\tpublic R assemble(RowProcessingState rowProcessingState) {\n\t\tfinal int numberOfArgs = argumentReaders.size();\n\t\tfinal var args = new Object[ numberOfArgs ];\n\t\tfor ( int i = 0; i < numberOfArgs; i++ ) {\n\t\t\targs[i] = argumentReaders.get( i ).assemble( rowProcessingState );\n\t\t}\n\n\t\ttry {\n\t\t\treturn targetConstructor.newInstance( args );\n\t\t}\n\t\tcatch (InvocationTargetException e) {\n\t\t\tthrow new InstantiationException( \"Error instantiating class '\"\n\t\t\t\t\t+ targetConstructor.getDeclaringClass().getName() + \"'\", e.getCause() );\n\t\t}\n\t\tcatch (Exception e) {\n\t\t\tthrow new InstantiationException( \"Error instantiating class '\"\n\t\t\t\t\t+ targetConstructor.getDeclaringClass().getName() + \"'\", e );\n\t\t}\n\t}\n\n\t@Override\n\tpublic void resolveState(RowProcessingState rowProcessingState) {\n\t\tfor ( var argumentReader : argumentReaders ) {\n\t\t\targumentReader.resolveState( rowProcessingState );\n\t\t}\n\t}\n\n\t@Override\n\tpublic <X> void forEachResultAssembler(BiConsumer<Initializer<?>, X> consumer, X arg) {\n\t\tfor ( var argumentReader : argumentReaders ) {","sourceCodeStart":34,"sourceCodeEnd":70,"githubUrl":"https://github.com/hibernate/hibernate-orm/blob/fad1729dce015f908198d57a8d80274a30f905a5/hibernate-core/src/main/java/org/hibernate/sql/results/graph/instantiation/internal/DynamicInstantiationAssemblerConstructorImpl.java#L34-L70","documentation":"DynamicInstantiationAssemblerConstructorImpl.assemble() gathers all constructor arguments from the row and calls Constructor.newInstance(args). If the constructor itself throws, the InvocationTargetException is unwrapped and rethrown as InstantiationException(\"Error instantiating class '<class>'\") with your constructor's exception as the cause. The query, argument binding and reflection all worked - your code inside the DTO constructor failed.","triggerScenarios":"A `select new ...` constructor expression whose constructor throws for particular row values: NPE from unboxing a null argument, parsing/formatting inside the constructor (LocalDate.parse, valueOf), validation or Objects.requireNonNull on arguments, arithmetic on null or unexpected values.","commonSituations":"DTO constructors doing more than assignment (defensive null checks, normalization) that break on null aggregate results or empty strings; schema changes making columns nullable; constructors shared with other callers that assume non-null; unboxing null SUM()/MAX() results from empty groups.","solutions":["Read the cause exception and its stack trace - it identifies the failing line inside your constructor.","Make the constructor null-safe: accept object/wrapper types and handle null before unboxing or parsing.","Keep DTO constructors trivial (pure assignment); do normalization/derivation in factory methods or after the query returns.","Add an integration test running the query against data including null columns and empty tables."],"exampleFix":"// before\npublic SalesDto(Long id, double total) { // unboxing NPE when sum(amount) is null\n    this.ratio = total / base;\n}\n\n// after\npublic SalesDto(Long id, Double total) {\n    this.ratio = total == null ? 0d : total / base;\n}","handlingStrategy":"try-catch","validationCode":"// Prove the constructor is null-safe before using it in select new\nConstructor<SalesDto> ctor = SalesDto.class.getConstructor(Long.class, Double.class);\ntry {\n    ctor.newInstance(null, null); // exactly what an empty result set can produce\n} catch (InvocationTargetException e) {\n    throw new IllegalStateException(\"DTO constructor throws on nulls - will fail during select new\", e.getCause());\n}","typeGuard":null,"tryCatchPattern":"try {\n    List<SalesDto> rows = em.createQuery(\n        \"select new com.acme.SalesDto(o.id, sum(l.amount)) from Order o join o.lines l group by o.id\",\n        SalesDto.class).getResultList();\n} catch (org.hibernate.query.sqm.sql.internal.InstantiationException e) {\n    Throwable cause = e.getCause(); // the exception your constructor threw\n    // fix the constructor (null-handling), then retry\n}","preventionTips":["Keep select-new constructors assignment-only; move logic to factories or post-query mapping.","Use wrapper types for all constructor parameters so null aggregates bind instead of NPE on unboxing.","Test each projection query against an empty table and null-valued columns."],"tags":["hibernate","orm","dynamic-instantiation","constructor-expression","dto","null-safety","query-projection"],"backgroundTag":"dynamic-instantiation-constructor-failure","analyzedSha":"fad1729dce015f908198d57a8d80274a30f905a5","analyzedAt":"2026-08-22T04:13:57.527Z","schemaVersion":2},"datasetVersion":"2026-08-22T09:17:25.309Z"}