在下面的JPQL查询中,什么是错误的还是不正确的?

问题描述

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

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

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

解决方法

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

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

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

但是Blaze-Persistence不仅可以帮助您进行DTO映射,还可以使用一些更高级的SQL概念,在这种情况下,使用横向联接。

针对您的用例的DTO模型可能与Blaze-Persistence Entity-Views相似,如下所示:

@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