如何使用 SqlResultSetMapping 将 JPA NativeQuery 的结果集映射到 POJO [英] How to map the result set of a JPA NativeQuery to a POJO using SqlResultSetMapping

查看:81
本文介绍了如何使用 SqlResultSetMapping 将 JPA NativeQuery 的结果集映射到 POJO的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 @SqlResultSetMapping 和 @ConstructorResult 将本机查询的结果映射到 POJO.这是我的代码:

I am attempting to map the results of a Native query to a POJO using @SqlResultSetMapping with @ConstructorResult. Here is my code:

@SqlResultSetMapping(name="foo",
    classes = {
        @ConstructorResult(
                targetClass = Bar.class,
                columns = {
                    @ColumnResult(name = "barId", type = Long.class),
                    @ColumnResult(name = "barName", type = String.class),
                    @ColumnResult(name = "barTotal", type = Long.class)
                })
    })

public class Bar {

private Long barId;
private String barName;
private Long barTotal;

...

然后在我的 DAO 中:

And then in my DAO:

Query query = em.createNativeQueryBar(QUERY, "foo");
... set some parameters ...
List<Bar> list = (List<Bar>) query.getResultList();

我已经读到此功能仅在 JPA 2.1 中受支持,但这就是我正在使用的.这是我的依赖:

I have read that this functionality is only supported in JPA 2.1, but that is what I am using. Here's my dependency:

        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.1-api</artifactId>
            <version>1.0.0.Final</version>
        </dependency>

我找到了一些资源,包括这个:@ConstructorResult mapping in jpa 2.1.但我仍然没有任何运气.

I found a couple of resources, including this one: @ConstructorResult mapping in jpa 2.1. But I am still not having any luck.

我错过了什么?为什么找不到SqlResultSetMapping?

What am I missing? Why can't the SqlResultSetMapping be found?

javax.persistence.PersistenceException: org.hibernate.MappingException: Unknown SqlResultSetMapping [foo]

推荐答案

@SqlResultSetMapping 注释不应放在 POJO 上.把它放在(任何)@Entity 类中.Unknown SqlResultSetMapping [foo]"告诉您,JPA 提供程序在名称foo"下看不到任何映射.请参阅我的另一个答案以获取正确示例

@SqlResultSetMapping annotation should not be put on a POJO. Put it at (any) @Entity class. "Unknown SqlResultSetMapping [foo]" tells you, that JPA provider doesn't see any mapping under name 'foo'. Please see another answer of mine for the correct example

这篇关于如何使用 SqlResultSetMapping 将 JPA NativeQuery 的结果集映射到 POJO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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