【问题标题】:Load child collection DTOs in JPA DTO projection query在 JPA DTO 投影查询中加载子集合 DTO
【发布时间】:2019-02-26 09:13:33
【问题描述】:

我在 Wildfly 10.1.0-Final 上使用 Java EE 7 和 Java 8 和 Hibernate (5.0.X),我需要使用投影将 JPQL 查询结果加载到 DTO 中,但我找不到任何文档以及如何加载子集合 DTO。

例如,如果我有以下用户、角色和权限实体:

@Entity
public class User
{
    @Id
    private long id;

    private String userName;
    private String firstName;
    private String lastName;

    private JobTitle jobTitle;
    private Email email;

    private boolean isRemote;

    @ManyToMany
    private Set<Tag> tags;

    @ManyToMany
    // @JoinColumn definitions...
    private Set<Role> roles;

    // getters/setters...
}

@Entity
public class Role
{
    @Id
    private long id;

    private String name;
    private String description;

    @ManyToMany
    // @JoinColumn definitions...
    private Set<Privilege> privileges;

    // getters/setters...
}

@Entity
public class Privilege
{
    @Id
    private long id;

    private String key;
    private String name;
    private String description;

    // getters/setters...
}

并且我想使用投影将一些查询结果加载到以下不可变 DTO 中(假设都具有基于 id 实现的 hashCode 和 equals):

public class UserDTO
{
    private final long id;
    private final String userName;
    private final Set<RoleDTO> roles = new HashSet<>();

    public UserDTO(long id, String userName, Collection<RoleDTO> roles) // not sure if this is correct for projection..
    {
        this.id = id;
        this.userName = userName;
        this.roles.addAll(roles);
    }

    public Set<Role> getRoles()
    {
         return Collections.unmodifiableSet(roles);
    }

    // getters
}

public class RoleDTO
{
    private final long id;
    private final String name;
    private final Set<PrivilegeDTO> privileges = new HashSet<>();

    public RoleDTO(long id, String name, Set<PrivilegeDTO> privileges)
    {
        this.id = id;
        this.name = name;
        this.privileges.addAll(privileges);
    }

    public Set<Privilege> getPrivileges()
    {
         return Collections.unmodifiableSet(privileges);
     }
    // other getters
}

public class PrivilegeDTO
{
    private final long id;
    private final String key;

    public PrivilegeDTO(long id, String key)
    {
        this.id = id;
        this.key = key;
    }
    // getters
}

实现这一点的 JPQL 查询结构应该是什么样的?我很确定我可以通过执行连接然后将结果处理到 DTO 对象中来完成工作,就像这样(按 ID 加载 50 个最新用户):

List<Object[]> results = em.createQuery("SELECT u.id, u.userName, r.id, "
    + "r.name, p.id, p.key FROM User u "
    + "LEFT JOIN u.roles r "
    + "LEFT JOIN r.privileges p "
    + "ORDER BY u.id DESC")
    .setMaxResults(50).getResultList();
Map<Long, UserDTO> users = new HashMap<>();
Map<Long, RoleDTO> roles = new HashMap<>();
Map<Long, PrivilegeDTO> privileges = new HashMap<>();

for(Object[] objArray : results)
{
  // process these into the DTO objects,
}

重建必须从 PrivilegeDTO 对象开始,然后是 RoleDTO,最后是 UserDTO。这将允许不变性,因为您在构建 RoleDTO 对象时需要 PrivilegeDTO 对象,或者您必须稍后添加它们,这意味着 RoleDTO 不是不可变的。

这将是 Streams 中的一个有趣的练习,但我更希望能够从查询中构建它,看起来它必须更快。这可能吗?

非常感谢!

【问题讨论】:

  • 一天结束时你想要什么????您有疑问在这里还需要什么?

标签: java jpa jpql projection


【解决方案1】:

嗨,Morgan 简短的回答是否定的,您不能从查询中构建,因为您不能将 JPQL 映射到 DTO 集合字段。这是一个与JPQL: Receiving a Collection in a Constructor Expression相关的问题

无论如何,您都可以尝试使用 spel https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query.spel-expressions 进行 Spring 投影的方法

但我认为正确的解决方案是使用手动映射,就像这个答案https://stackoverflow.com/a/45934668/3449039中解释的那样

【讨论】:

    【解决方案2】:

    这不可能像 lucsbelt 已经回答的那样开箱即用,但我认为这是 Blaze-Persistence Entity Views 的完美用例。

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

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

    @EntityView(User.class)
    public interface UserDTO {
        @IdMapping
        Long getId();
        String getUserName();
        Set<RoleDto> getRoles();
    
        @EntityView(Role.class)
        interface RoleDto {
            @IdMapping
            Long getId();
            String getName();
            // To avoid the cartesian product, use a fetch strategy other than JOIN
            @Mapping(fetch = FetchStrategy.MULTISET)
            Set<PrivilegeDto> getPrivileges();
        }
    
        @EntityView(Privilege.class)
        interface PrivilegeDto {
            @IdMapping
            Long getId();
            String getKey();
        }
    }
    

    查询是将实体视图应用于查询的问题,最简单的就是通过 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

    Page<UserDTO> findAll(Pageable pageable);
    

    最好的部分是,它只会获取实际需要的状态!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-18
      • 2019-08-11
      • 2018-03-05
      • 1970-01-01
      • 1970-01-01
      • 2015-01-25
      相关资源
      最近更新 更多