@@ -134,6 +134,8 @@ public class NativeQueryImpl<R>
134134 private Set <String > querySpaces ;
135135 private Callback callback ;
136136
137+ private Class resultEntityClass ;
138+
137139 /**
138140 * Constructs a NativeQueryImpl given a sql query defined in the mappings.
139141 */
@@ -218,12 +220,19 @@ public NativeQueryImpl(
218220 session
219221 );
220222
223+ if ( resultJavaType != null && getSessionFactory ().getMappingMetamodel ().isEntityClass ( resultJavaType ) ) {
224+ resultEntityClass = resultJavaType ;
225+ }
226+
221227 if ( resultJavaType == Tuple .class ) {
222228 setTupleTransformer ( new NativeQueryTupleTransformer () );
223229 }
224230 else if ( resultJavaType != null && !resultJavaType .isArray () ) {
225231 switch ( resultSetMapping .getNumberOfResultBuilders () ) {
226232 case 0 : {
233+ if (resultEntityClass != null ) {
234+ break ;
235+ }
227236 throw new IllegalArgumentException ( "Named query exists, but did not specify a resultClass" );
228237 }
229238 case 1 : {
@@ -354,6 +363,10 @@ private static ResultSetMapping buildResultSetMapping(
354363 return ResultSetMapping .resolveResultSetMapping ( registeredName , isDynamic , session .getFactory () );
355364 }
356365
366+ public void setResultEntityClass (Class <?> resultEntityClass ) {
367+ this .resultEntityClass = resultEntityClass ;
368+ }
369+
357370 public List <ParameterOccurrence > getParameterOccurrences () {
358371 return parameterOccurrences ;
359372 }
@@ -459,7 +472,7 @@ public QueryParameterBindings getParameterBindings() {
459472 public NamedNativeQueryMemento <?> toMemento (String name ) {
460473 return new NamedNativeQueryMementoImpl <>(
461474 name ,
462- extractResultClass ( resultSetMapping ),
475+ resultEntityClass != null ? resultEntityClass : extractResultClass ( resultSetMapping ),
463476 sqlString ,
464477 originalSqlString ,
465478 resultSetMapping .getMappingIdentifier (),
@@ -644,6 +657,18 @@ public KeyedResultList<R> getKeyedResultList(KeyedPage<R> page) {
644657 }
645658
646659 protected SelectQueryPlan <R > resolveSelectQueryPlan () {
660+ if ( resultEntityClass != null ) {
661+ boolean exists = false ;
662+ for ( ResultBuilder existing : resultSetMapping .getResultBuilders () ) {
663+ if ( resultEntityClass == existing .getJavaType () ) {
664+ exists = true ;
665+ break ;
666+ }
667+ }
668+ if ( !exists ) {
669+ addEntity ( (Class <R >) resultEntityClass , LockMode .READ );
670+ }
671+ }
647672 if ( isCacheableQuery () ) {
648673 final QueryInterpretationCache .Key cacheKey = generateSelectInterpretationsKey ( resultSetMapping );
649674 return getSession ().getFactory ().getQueryEngine ().getInterpretationCache ()
0 commit comments