java - 在 JPA 查询中从 GROUP BY 创建 Map 对象

标签 java spring spring-boot hibernate spring-data-jpa

为了简单起见,我有 3 个表:

  • 公司
  • 员工
  • 设备

公司有员工,每个员工都分配有许多设备。我对连接到他们分配给员工的设备名称列表的 companyId 列表感兴趣。

Java 对象示例:

@Getter
@Setter
@AllArgsConstructor
public class CompanyDevices {
  private Long companyId;
  private List<String> deviceNames;
}

或者更好的是 map 会很棒: Map

是否可以在 JPARepository 中使用 @Query 创建 JPA 查询、连接所有这些表并返回自定义对象列表或映射?

我现在拥有的类别略有不同:

@Getter
@Setter
@AllArgsConstructor
public class CompanyDevice {
  private Long companyId;
  private String deviceName;
}
public interface SomeRepository extends JpaRepository<SomeEntity, Long> {
    
    @Query("SELECT " +
            "new path.to.CompanyDevice(C.id, D.deviceName) " +
            "FROM Company C " +
            "JOIN C.employees E " +
            "JOIN E.devices D " +
            "WHERE C.id IN :companyIds"
    )
    List<CompanyDevice> findDevicesForCompanies(@Param("companyIds") List<Long> companyIds);

}

因此,我需要稍后手动分组并创建 map 。所以我想做的是这样的事情,但我只是找不到足够的信息,或者甚至可能不可能(抱歉伪代码):

public interface SomeRepository extends JpaRepository<SomeEntity, Long> {
    
    @Query("SELECT " +
            "<create map where key is C.id and value is <list of D.deviceName from grouping>>" +
            "FROM Company C " +
            "JOIN C.employees E " +
            "JOIN E.devices D " +
            "WHERE C.id IN :companyIds" +
            "GROUP BY C.id"
    )
    Map<Long, List<String>> findDevicesForCompanies(@Param("companyIds") List<Long> companyIds);

}

最佳答案

您需要的是这样的中间函数:

public interface SomeRepository extends JpaRepository<SomeEntity, Long> {
    
    @Query("SELECT " +
            "c.id, d.deviceName " +
            "FROM Company c " +
            "JOIN c.employees e " +
            "JOIN e.devices d " +
            "WHERE c.id IN :companyIds"
    )
    List<Object[]> findDevicesForCompanies0(@Param("companyIds") List<Long> companyIds);

    default Map<Long, List<String>> findDevicesForCompanies(List<Long> companyIds) {
        return findDevicesForCompanies(companyIds).stream()
            .collect(
                Collectors.groupingBy(
                    o -> (Long) o[0],
                    Collectors.mapping( o -> (String) o[1], Collectors.toList() )
                )
            );
    }

}

解决这个问题的另一个好方法是使用 Blaze-Persistence Entity Views我认为这是一个完美的用例。

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

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

@EntityView(Company.class)
public interface CompanyDevices {
    @IdMapping
    Long getId();
    @Mapping("employees.devices.deviceName")
    Set<String> getDeviceNames();
}

查询是将实体 View 应用于查询,最简单的是通过 id 进行查询。

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

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

Page<CompanyDevices> findAll(Pageable pageable);

或者根据您的具体情况

List<CompanyDevices> findByIdIn(List<Long> companyIds);

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

关于java - 在 JPA 查询中从 GROUP BY 创建 Map 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69531153/

相关文章:

java - 如何从 java 中的 URL 读取 XML 响应?

java - 如何在 fragment 中请求 WRITE_EXTERNAL_STORAGE 权限

java - Spring 与 HSQLDB 最新 2.4.0 版本不工作

java - Spring NamedParameterJdbcTemplate batchUpdate - 一次错误插入导致整个批处理失败

java - 使用 Swagger 进行身份验证登录

java - 请求调度概念的包含和转发机制之间的区别?

java - 无法在真实设备上的 iOS 10 上运行 Appium 测试

spring - 在没有 Spring Boot 的情况下创建上下文后防止 Spring Batch 自 Action 业触发

mysql - 'where clause' 中的 Spring 未知列

java - 带有 mongodb PostAuthorize 和 PreAuthorize 的 Spring Boot 安全性不起作用