如何使用JpaRepository在xml中使用命名的nativ查询返回Map作为结果

时间:2017-10-19 13:18:45

标签: sql spring jpa named-query

我需要每天查询一些计数,我想创建命名的本机查询,它将在地图中返回。我怎么能这样做?

<named-native-query name="getLeadNumberByDayInDateRange" result-set-mapping="map">
            <query>
                SELECT addeddate, 
                       Count(DISTINCT campaignid, email) AS count 
                FROM   leads 
                GROUP  BY addeddate   
            </query>
        </named-native-query>

所以我在xml中编写查询,我想将其添加到JpaRepository中:

@Query
public Map<LocalDateTime, Integer> getLeadNumberByDayInDateRange();

1 个答案:

答案 0 :(得分:2)

要使用命名查询执行此操作,可以执行以下操作:

@Query("SELECT l.addeddate, Count(DISTINCT l.campaignid)
        FROM leads l 
        GROUP BY l.addeddate")
public Map<LocalDateTime, Integer> getLeadNumberByDayInDateRange();

或类似的东西:

@NamedQuery(name = "getLeadNumberByDayInDateRange", 
query = "SELECT l.addeddate, Count(DISTINCT l.campaignid)
         FROM leads l 
         GROUP BY l.addeddate")
public Map<LocalDateTime, Integer> getLeadNumberByDayInDateRange();

或者如果你想要一些自定义映射,你可以使用[sql result set mappings]。1