2017-07-02 27 views
2

我正在使用Spring + Hibernate,我有一個特殊的情況,我需要獲取(列表)非Entity對象作爲查詢的結果。@NamedNativeQuery - 如何將它綁定到存儲庫方法?

我決定在@SqlResultSetMapping中使用@ConstructorResult,如herehere所述,參照@NamedNativeQuery中的該映射。

然而,在使用命名原生查詢所有的例子,他們通過@PersistenceContext獲得EntityManager實例,並調用createNativeQuery上,提供@NamedNativeQuery作爲參數的name這一號召,爲this答案可見。

如何將存儲庫中的聲明方法interface映射到特定的@NamedNativeQuery?我的嘗試是使用EntityName.MethodNameInRepositoryMethodNameInRepository作爲@NamedNativeQueryname,但沒有運氣。

這裏是我的簡化代碼:

@Entity(name = "AdDailyData") 
@SqlResultSetMapping(
     name="RevenueByAppAndDayMapping", 
     [email protected](
       targetClass=RevenueByAppAndDay.class, 
       columns={@ColumnResult(name="country_code"), 
         @ColumnResult(name="revenue", type=Double.class), 
         @ColumnResult(name="currency")})) 
@NamedNativeQuery(
     name="AdDailyData.aggregateRevenue", 
     query="SELECT country_code, sum(earnings) as revenue, currency " 
       + "FROM ad_daily_data, pseudo_app, app " 
       + "WHERE ad_daily_data.pseudo_app_id=pseudo_app.id AND pseudo_app.app_id=app.id AND app.id=:appId and ad_daily_data.day = :day " 
       + "GROUP BY country_code, currency " 
       + "ORDER BY country_code ASC", 
     resultSetMapping="RevenueByAppAndDayMapping") 
public class AdDailyDataEntity { 

    // fields, getters, setters etc. 

    public static interface Repository extends JpaRepository<AdDailyDataEntity, Long> { 

     public List<RevenueByAppAndDay> aggregateRevenue(@Param("appId") long appId, @Param("day") LocalDate day); 

    } 

} 

這裏是我的非Entity類。

public class RevenueByAppAndDay { 

    private String countryCode; 
    private Double earnings; 
    private String currency; 

    public RevenueByAppAndDay(String countryCode, Double earnings, String currency) { 
     this.countryCode = countryCode; 
     this.earnings = earnings; 
     this.currency = currency; 
    } 

    public String getCountryCode() { 
     return countryCode; 
    } 

    public Double getEarnings() { 
     return earnings; 
    } 

    public String getCurrency() { 
     return currency; 
    } 

} 

任何形式的幫助,高度讚賞。

編輯: 堆棧跟蹤的端部如下:

Caused by: org.springframework.data.mapping.PropertyReferenceException: No property aggregateRevenue found for type AdDailyDataEntity! 
+0

你可以添加你收到的堆棧跟蹤嗎? –

+0

@GrantLay添加了異常。 – ram

+0

如何從服務調用aggregateRevenue?我試過自動裝配AdDailyDataEntity並調用adDailyDataEntity.aggregateRevenue,但是我得到一個錯誤,說明方法未定義。 –

回答

3

@NamedNativeQuery需要的name值被設置爲"AdDailyDataEntity.aggregateRevenue"。第一部分(點之前)需要匹配實體類名稱。