将原生查询结果映射到非实体

将原生查询结果映射到非实体

本文介绍了Spring Data JPA 将原生查询结果映射到非实体 POJO的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有本机查询的 Spring Data 存储库方法

I have a Spring Data repository method with a native query

@Query(value = "SELECT g.*, gm.* FROM group g LEFT JOIN group_members gm ON g.group_id = gm.group_id and gm.user_id = :userId WHERE g.group_id = :groupId", nativeQuery = true)
GroupDetails getGroupDetails(@Param("userId") Integer userId, @Param("groupId") Integer groupId);

我想将结果映射到非实体 POJO GroupDetails.

and I'd like to map the result to Non-Entity POJO GroupDetails.

可以吗,如果可以,能否举个例子?

Is it possible and if so, could you please provide an example ?

推荐答案

假设 Orid 的答案中的 GroupDetails 你试过 JPA 2.1 @ConstructorResult?

Assuming GroupDetails as in orid's answer have you tried JPA 2.1 @ConstructorResult?

@SqlResultSetMapping(
    name="groupDetailsMapping",
    classes={
        @ConstructorResult(
            targetClass=GroupDetails.class,
            columns={
                @ColumnResult(name="GROUP_ID"),
                @ColumnResult(name="USER_ID")
            }
        )
    }
)

@NamedNativeQuery(name="getGroupDetails", query="SELECT g.*, gm.* FROM group g LEFT JOIN group_members gm ON g.group_id = gm.group_id and gm.user_id = :userId WHERE g.group_id = :groupId", resultSetMapping="groupDetailsMapping")

并在存储库界面中使用以下内容:

and use following in repository interface:

GroupDetails getGroupDetails(@Param("userId") Integer userId, @Param("groupId") Integer groupId);

根据 Spring Data JPA 文档,spring 将首先尝试找到与您的方法名称匹配的命名查询 - 因此通过使用 @NamedNativeQuery@SqlResultSetMapping@ConstructorResult你应该能够实现这种行为

According to Spring Data JPA documentation, spring will first try to find named query matching your method name - so by using @NamedNativeQuery, @SqlResultSetMapping and @ConstructorResult you should be able to achieve that behaviour

这篇关于Spring Data JPA 将原生查询结果映射到非实体 POJO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 07:13