복붙노트

[SPRING] @ NamedNativeQuery - 어떻게 그것을 리포지토리 메서드에 바인딩 할 수 있습니까?

SPRING

@ NamedNativeQuery - 어떻게 그것을 리포지토리 메서드에 바인딩 할 수 있습니까?

나는 Spring + Hibernate를 사용하고 있으며 쿼리의 결과로 비 Entity 객체 (리스트)를 얻을 필요가있는 특별한 경우가있다.

@SqlResultSetMapping에서 @ConstructorResult를 사용하고 여기에 언급 된 @NamedNativeQuery에서이 매핑을 참조하기로 결정했습니다.

그러나 명명 된 네이티브 쿼리를 사용하는 모든 예제에서 @PersistenceContext를 통해 EntityManager 인스턴스를 가져오고 createNativeQuery를 호출하여이 응답에 표시된대로 해당 호출의 매개 변수로 @NamedNativeQuery 이름을 제공합니다.

저장소 인터페이스에서 선언 된 메소드를 특정 @NamedNativeQuery에 어떻게 맵핑 할 수 있습니까? 내 시도는 EntityName.MethodNameInRepository 또는 MethodNameInRepository를 @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. ==============================

    1.@NamedNativeQuery의 이름 값은 "AdDailyDataEntity.aggregateRevenue"로 설정되어야합니다. 첫 번째 부분 (점 앞에)은 엔티티 클래스 이름과 일치해야합니다.

    @NamedNativeQuery의 이름 값은 "AdDailyDataEntity.aggregateRevenue"로 설정되어야합니다. 첫 번째 부분 (점 앞에)은 엔티티 클래스 이름과 일치해야합니다.

  2. from https://stackoverflow.com/questions/44871757/namednativequery-how-can-i-bind-it-to-a-repository-method by cc-by-sa and MIT license