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

Create Map object from GROUP BY in JPA Query

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

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

示例 Java 对象:

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

或者更好的地图会更好: Map

甚至可以创建 JPA 查询、连接所有这些表和 return 自定义对象列表或在 JPARepository 中使用 @Query 的地图吗?

我现在拥有的略有不同class:

@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);

}

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

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 模型和自定义接口或抽象 class 定义的模型之间轻松映射,类似于 Spring 类固醇数据投影。这个想法是您按照自己喜欢的方式定义目标结构(领域模型),并通过 JPQL 表达式将属性(getter)映射到实体模型。

您的用例的 DTO 模型与 Blaze-Persistence 实体视图类似:

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

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

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

Spring 数据集成让您几乎可以像 Spring 数据投影一样使用它: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);

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