JPA:如何将本机查询结果集转换为 POJO 类集合 [英] JPA : How to convert a native query result set to POJO class collection

查看:27
本文介绍了JPA:如何将本机查询结果集转换为 POJO 类集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的项目中使用 JPA.

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.

现在我想将结果对象转换为包含相同五个字符串的 java POJO 类.

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

JPA 有没有办法直接将结果转换为 POJO 对象列表??

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  
})  

现在在 resultClass 中,我们是否需要提供一个实际的 JPA 实体类?或者我们可以将其转换为任何包含相同列名的 JAVA POJO 类吗?

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 ?

推荐答案

JPA 提供了一个 SqlResultSetMapping 允许您将从本地查询返回的任何内容映射到实体 或自定义类.

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

EDIT JPA 1.0 不允许映射到非实体类.仅在 JPA 2.1 中,ConstructorResult 已添加到地图返回一个 java 类的值.

EDIT 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.

此外,对于 OP 获取计数的问题,定义一个结果集映射就足够了,ColumnResult

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

这篇关于JPA:如何将本机查询结果集转换为 POJO 类集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆