如何解决在下面的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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。