![](/img/trans.png)
[英]How to return a custom object from a Spring Data JPA GROUP BY query
[英]Create Map object from GROUP BY in JPA Query
為簡單起見,我有 3 個表:
公司有員工,每個員工都有許多分配給他們的設備。 我對連接到他們分配給員工的設備名稱列表的 companyId 列表感興趣。
示例 Java 對象:
@Getter
@Setter
@AllArgsConstructor
public class CompanyDevices {
private Long companyId;
private List<String> deviceNames;
}
或者甚至更好的 Map 會很棒:Map<Long, List 其中 Long 將是 companyId,List 將是 deviceNames;
甚至可以在 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);
}
因此,我需要稍后手動分組並創建地圖。 所以我想做的是這樣的事情,但我找不到足夠的信息,或者甚至可能不可能(對不起,偽代碼):
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 模型和自定義接口或抽象類定義的模型之間輕松映射,例如類固醇上的 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();
}
查詢是將實體視圖應用於查詢的問題,最簡單的只是按 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);
最好的部分是,它只會獲取實際需要的狀態!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.