Spring数据jpa。按操作分组返回地图

时间:2015-06-24 08:29:31

标签: spring jpa spring-data spring-data-jpa

我的jpa存储库界面中有一个查询。

@Query("select e.campaignId, e from CampaignCrTargetingProfile e where e.campaignId in :ids group by e.campaignId")
public Map<Integer, List<CampaignCrTargetingProfile>> findByCampaignIdIn(@Param("ids") Iterable<Integer> ids);

campaignId是整数。

但是当我尝试执行此查询时,我发现了异常。

Caused by: org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type java.lang.Integer to type java.util.Map<?, ?>
at org.springframework.core.convert.support.GenericConversionService.handleConverterNotFound(GenericConversionService.java:311) ~[spring-core-4.1.5.RELEASE.jar:4.1.5.RELEASE]
at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:192) ~[spring-core-4.1.5.RELEASE.jar:4.1.5.RELEASE]
at org.springframework.core.convert.support.ArrayToObjectConverter.convert(ArrayToObjectConverter.java:66) ~[spring-core-4.1.5.RELEASE.jar:4.1.5.RELEASE]
at org.springframework.core.convert.support.ConversionUtils.invokeConverter(ConversionUtils.java:35) ~[spring-core-4.1.5.RELEASE.jar:4.1.5.RELEASE]
... 192 common frames omitted

是否有可能通过其字段摸索entites并将结果返回为Map?如果不可能,还有另一种方法可以做出类似的事情吗?

1 个答案:

答案 0 :(得分:0)

您可能会从JPQL查询中获得一个列表,然后使用Java 8 Stream API将其转换为地图。

// This method in your Repository interface
@Query("SELECT e FROM CampaignCrTargetingProfile e WHERE e.campaignId IN :ids")
public List<CampaignCrTargetingProfile findByCampaignIdIn(@Param("ids") Iterable<Integer> ids);

// This source from your Service class
List<CampaignCrTargetingProfile> list = repo.findByCampaignIdIn(iterableArg);
Map<Integer, List<CampaignCrTargetingProfile>> mapResult = list.stream()
    .collect(Collectors.groupingBy(CampaignCrTargetingProfile::getCampaignId));