我正在使用Spring + Hibernate,在特殊情况下,由于查询,我需要获取(列表)非Entity对象。

我决定在@ConstructorResult中使用@SqlResultSetMapping,并在@NamedNativeQuery中引用此映射,如herehere所述。

但是,在所有使用命名 native 查询的示例中,它们都通过EntityManager获取@PersistenceContext实例,并在其上调用createNativeQuery,并将name@NamedNativeQuery提供为该调用的参数,如this答案所示。

如何将在存储库interface中声明的方法映射到特定的@NamedNativeQuery?我的尝试是使用EntityName.MethodNameInRepositoryMethodNameInRepository作为name@NamedNativeQuery,但是没有运气。

这是我的简化代码:

@Entity(name = "AdDailyData")
@SqlResultSetMapping(
        name="RevenueByAppAndDayMapping",
        classes=@ConstructorResult(
                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!

最佳答案

name上的@NamedNativeQuery值需要设置为"AdDailyDataEntity.aggregateRevenue"。第一部分(点前)需要与实体类名称匹配。

07-26 03:56