我正在使用Spring
+ Hibernate
,我有一個特殊的情況,我需要獲取(列表)非Entity
對象作爲查詢的結果。@NamedNativeQuery - 如何將它綁定到存儲庫方法?
我決定在@SqlResultSetMapping
中使用@ConstructorResult
,如here和here所述,參照@NamedNativeQuery
中的該映射。
然而,在使用命名原生查詢所有的例子,他們通過@PersistenceContext
獲得EntityManager
實例,並調用createNativeQuery
上,提供@NamedNativeQuery
作爲參數的name
這一號召,爲this答案可見。
如何將存儲庫中的聲明方法interface
映射到特定的@NamedNativeQuery
?我的嘗試是使用EntityName.MethodNameInRepository
或MethodNameInRepository
作爲@NamedNativeQuery
的name
,但沒有運氣。
這裏是我的簡化代碼:
@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!
你可以添加你收到的堆棧跟蹤嗎? –
@GrantLay添加了異常。 – ram
如何從服務調用aggregateRevenue?我試過自動裝配AdDailyDataEntity並調用adDailyDataEntity.aggregateRevenue,但是我得到一個錯誤,說明方法未定義。 –