@NamedNativeQuery - 如何将其绑定到存储库方法?

2022-09-02 13:42:35

我正在使用+,并且我有一个特殊情况,我需要获取(列表)非对象作为查询的结果。SpringHibernateEntity

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

但是,在使用命名本机查询的所有示例中,它们通过获取实例并调用它,为该调用提供 of as 参数,如答案所示。EntityManager@PersistenceContextcreateNativeQueryname@NamedNativeQuery

如何将存储库中声明的方法映射到特定方法?我的尝试是使用或作为 的,但没有运气。interface@NamedNativeQueryEntityName.MethodNameInRepositoryMethodNameInRepositoryname@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!

答案 1

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


答案 2

虽然答案是正确的,但对于到达这里的人来说,这适用于我,而无需使用@NamedNativeQuery:

public class Example {

private Long someProperty;
// getters and setters
}

调用查询或存储过程并填充我的对象:

@Repository
public interface ExampleRepository extends 
JpaRepository<Example,Long> {

/**
 * Search Example by someProperty
 *
 * @param property
 * @return
 */
@Query( nativeQuery = true, value = "SELECT * FROM public.my_stored_procedure(:property)")
List<Example> findByProperty(@Param("property") Long property);

}

我知道这是另一种方法,代码是解耦的,但我们得到相同的结果。

我希望这对某人有用。问候。


推荐