【问题标题】:How to Use JPA map native query into nested projection如何使用 JPA 将本机查询映射到嵌套投影
【发布时间】:2021-01-08 02:13:42
【问题描述】:

我有两个表,用户和角色,它们是多对多

它们也是大表,不要指望所有不相关的列返回。

所以我有本机查询,(并且必须使用本机)。

select u.name, r.name, r.uuid
from user u
       join user_role_join urj on urj.user_uuid = u.uuid
       join role r on r.uuid = urj.role_uuid;

从返回开始,一个用户显示多个角色。

Adam | superAdmin | {uuid1}
Adam | admin      | {uuid2}
Lisa | guest      | {uuid3}
...

我需要退货以适应 pojo

User
 String name,
 List<Role> roles;

Role
 String name,
 UUID uuid

我正在使用 EntityManager 进行查询。

我如何让 JPA 知道将一个用户映射到多个角色?

{
 name:Adam
 roles:[
 {
   uuid:{uuid1}
   name:superAdmin
 },
 {
   uuid:{uuid2}
   name:admin
 }
 ]
},
{
 name:Lisa
 roles:[
 {
   uuid:{uuid3}
   name:guest
 }
 ]
} 

【问题讨论】:

    标签: java hibernate jpa entitymanager


    【解决方案1】:

    我不知道你为什么需要使用原生查询,但是当涉及到集合时,JPA/Hibernate 只能在使用实体时帮助你。

    如果您想避免不必要的选择项,我建议您尝试使用带有 Blaze-Persistence 的 JPA 模型,因为这是 Blaze-Persistence Entity Views 的完美用例。

    我创建了该库以允许在 JPA 模型和自定义接口或抽象类定义模型之间轻松映射,例如 Spring Data Projections on steroids。这个想法是您按照自己喜欢的方式定义目标结构(域模型),并通过 JPQL 表达式将属性(getter)映射到实体模型。

    使用 Blaze-Persistence Entity-Views 的用例的 DTO 模型可能如下所示:

    @EntityView(User.class)
    public interface UserDto {
        @IdMapping
        UUID getId();
        String getName();
        Set<RoleDto> getRoles();
    
        @EntityView(Role.class)
        interface RoleDto {
            @IdMapping
            UUID getUuid();
            String getName();
        }
    }
    

    查询是将实体视图应用于查询的问题,最简单的就是通过 id 进行查询。

    UserDto a = entityViewManager.find(entityManager, UserDto.class, id);

    Spring Data 集成让您可以像使用 Spring Data Projections 一样使用它:https://persistence.blazebit.com/documentation/entity-view/manual/en_US/index.html#spring-data-features

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-16
      • 1970-01-01
      • 2017-01-02
      • 1970-01-01
      • 2014-07-06
      • 2022-01-11
      相关资源
      最近更新 更多