@@ -328,24 +328,35 @@ private void handleExplicitResultSetMapping() {
328328 setTupleTransformerForResultType ( resultType );
329329 }
330330 else {
331- checkResultType ( resultType );
331+ checkResultType ( resultType , resultSetMapping );
332332 }
333333 }
334334 }
335335
336- private void checkResultType (Class <R > resultType ) {
337- switch ( resultSetMapping .getNumberOfResultBuilders () ) {
338- case 0 :
339- throw new IllegalArgumentException ( "Named query exists, but did not specify a resultClass" );
340- case 1 :
341- final Class <?> actualResultJavaType =
342- resultSetMapping .getResultBuilders ().get ( 0 ).getJavaType ();
343- if ( actualResultJavaType != null && !resultType .isAssignableFrom ( actualResultJavaType ) ) {
344- throw buildIncompatibleException ( resultType , actualResultJavaType );
345- }
346- break ;
347- default :
348- throw new IllegalArgumentException ( "Cannot create TypedQuery for query with more than one return" );
336+ private void checkResultType (Class <R > resultType , ResultSetMapping resultSetMapping ) {
337+ // resultType can be null if any of the deprecated methods were used to create the query
338+ if ( resultType != null && !isResultTypeAlwaysAllowed ( resultType )) {
339+ switch ( resultSetMapping .getNumberOfResultBuilders () ) {
340+ case 0 :
341+ if ( !resultSetMapping .isDynamic () ) {
342+ throw new IllegalArgumentException ( "Named query exists, but did not specify a resultClass" );
343+ }
344+ break ;
345+ case 1 :
346+ final Class <?> actualResultJavaType =
347+ resultSetMapping .getResultBuilders ().get ( 0 ).getJavaType ();
348+ if ( actualResultJavaType != null && !resultType .isAssignableFrom ( actualResultJavaType ) ) {
349+ throw buildIncompatibleException ( resultType , actualResultJavaType );
350+ }
351+ break ;
352+ default :
353+ for ( ResultBuilder resultBuilder : resultSetMapping .getResultBuilders () ) {
354+ final Class rbJavaType = resultBuilder .getJavaType ();
355+ if ( !resultType .isAssignableFrom ( rbJavaType ) ) {
356+ throw new IllegalArgumentException ( "The result set mapping of the typed query doesn't match the declared return type" );
357+ }
358+ }
359+ }
349360 }
350361 }
351362
@@ -716,6 +727,7 @@ else if ( !isResultTypeAlwaysAllowed( resultType )
716727 else {
717728 mapping = resultSetMapping ;
718729 }
730+ checkResultType ( resultType , mapping );
719731 return isCacheableQuery ()
720732 ? getInterpretationCache ()
721733 .resolveSelectQueryPlan ( selectInterpretationsKey ( mapping ), () -> createQueryPlan ( mapping ) )
0 commit comments