Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Java by (10.2k points)

I am using JPA in my project.

I came to a query in which I need to make join operation on five tables. So I created a native query which returns five fields.

Now I want to convert the result object to java POJO class which contains the same five Strings.

Is there any way in JPA to directly cast that result to POJO object list ??

I came to the following solution ..

@NamedNativeQueries({  

    @NamedNativeQuery(  

        name = "nativeSQL",  

        query = "SELECT * FROM Actors",  

        resultClass = db.Actor.class),  

    @NamedNativeQuery(  

        name = "nativeSQL2",  

        query = "SELECT COUNT(*) FROM Actors",  

        resultClass = XXXXX) // <--------------- problem  

})  

Now here in resultClass, do we need to provide a class which is actual JPA entity ? OR We can convert it to any JAVA POJO class which contains the same column names ?

1 Answer

0 votes
by (46k points)

JPA provides an SqlResultSetMapping that allows you to map whatever returns from your native query into an Entity or a custom class.

JPA 1.0 does not allow mapping to non-entity classes. Only in JPA 2.1 a ConstructorResult has been added to map return values a java class.

Also, for OP's problem with getting count it should be enough to define a result set mapping with a single ColumnResult

Related questions

0 votes
1 answer
0 votes
1 answer
asked Nov 23, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
0 votes
1 answer
asked Jul 22, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer

Browse Categories

...