0

下面是我写的 JPQL 查询,但它不起作用。我收到以下错误:NoViableAltException:意外令牌:最大

有人可以指出以下查询中的错误吗?

SELECT new com.chp.cef.api.dto.EventSearchDTO(ec.eventName, e.eventKey, e.eventTime, CAST(e.messagePayload AS string), epl.status, epl.statusReason, CAST(epl.processLogPayload AS string), ec.source, " +
            "epl.eventProcessLogKey, epl.eventReceivedTime, epl.eventProcessedTime) FROM Event e " +
            "left join (SELECT inEpl.eventKey, max(inEpl.eventReceivedTime), inEpl.eventProcessLogKey, inEpl.status, inEpl.statusReason, inEpl.processLogPayload, inEpl.eventProcessedTime" +
            "FROM EventProcessLog inEpl GROUP BY inEpl.eventKey) epl ON e.eventKey = epl.eventKey " +
            "left join EventConfiguration ec ON e.eventConfigKey = ec.eventConfigurationKey WHERE ec.eventName = coalesce(:eventName, ec.eventName) " +
            "AND epl.status = coalesce(:eventStatus, epl.status) AND e.eventTime >= :eventStartTime AND e.eventTime <= :eventEndTime
4

1 回答 1

0

您不能在 JPQL/HQL 中加入子查询。您必须将其重新表述为 ON 子句中的相关子查询。

话虽如此,我认为这是Blaze-Persistence 实体视图的完美用例,它支持通过@Limit注释获取每个类别的 TOP-N。

我创建了该库以允许在 JPA 模型和自定义接口或抽象类定义模型之间轻松映射,例如 Spring Data Projections on steroids。这个想法是您以您喜欢的方式定义您的目标结构(域模型),并通过 JPQL 表达式将属性(getter)映射到实体模型。

但是 Blaze-Persistence 不仅可以帮助您进行 DTO 映射,还可以使用一些更高级的 SQL 概念,在本例中是横向连接。

使用 Blaze-Persistence Entity-Views 的用例的 DTO 模型可能如下所示:

@EntityView(Event.class)
public interface EventSearchDTO {
    @IdMapping
    String getEventKey();
    String getEventName();
    Instant getEventTime();
    @Mapping("CAST_STRING(messagePayload)")
    String getMessagePayload();
    // ...

    @Limit(limit = "1", order = "eventReceivedTime DESC")
    @Mapping("EventProcessLog[eventKey = VIEW(eventKey)]")
    // If you have an association mapping, can be simplified to
    // @Mapping("processLogs")
    EventProcessLogDto getLatestLog();

    @EntityView(EventProcessLog.class)
    interface EventProcessLogDto {
        @IdMapping
        String getEventKey();
        String getEventProcessLogKey();
        // ...
    }

    @Mapping("EventConfiguration[eventConfigurationKey = VIEW(eventConfigKey)]")
    EventConfigurationDto getConfiguration();

    @EntityView(EventConfiguration.class)
    interface EventConfigurationDto {
        @IdMapping
        String getEventConfigurationKey();
        // ...
    }
}

查询是将实体视图应用于查询的问题,最简单的就是通过 id 进行查询。

EventSearchDTO a = entityViewManager.find(entityManager, EventSearchDTO.class, id);

Spring Data 集成允许您几乎像 Spring Data Projections 一样使用它:https ://persistence.blazebit.com/documentation/entity-view/manual/en_US/index.html#spring-data-features

这将产生类似于以下的 SQL 查询

SELECT ec.eventName, ... 
FROM Event e
left join lateral (SELECT * FROM EventProcessLog inEpl WHERE e.eventKey = inEpl.eventKey ORDER BY inEpl.eventReceivedTime DESC LIMIT 1) epl ON 1=1
left join EventConfiguration ec ON e.eventConfigKey = ec.eventConfigurationKey
于 2020-09-29T06:20:49.903 回答