JPA CriteriaQuery无法找到日期差总和的适当构造函数



我知道这个问题看起来很相似,但我认为对我来说情况不同

这是异常消息

获取数据时出现异常(/periodicReport/userReport(:org.hibernate.hql.internal.ast.QuerySyntaxException:找不到类上的适当构造函数[com.analytic.intity.projections.UserParticipantCountAndDurationImpl]。预期参数为:java.util.UUID、long、java.util.Date[select新com.analytics.entity.projections.UserParticipantCountAndDurationImpl(generatedAlias0.userID,count(distinct generatedAlias0.userID(、sum(function('TIMEDIFF',generatedAlias0.endTime,generatedAlias0.startTime((com.analystics.entity.ConferenceParticipantgeneratedAlias0 group by generatedAlias0.userID order by:param0 desc]

我希望总和是Long,并且我已经在条件查询中指定了它。我不知道日期在哪里定义

内置的狙击手

Expression<Long> sum = criteriaBuilder.sum(
criteriaBuilder.function(
"TIMEDIFF",
Long.class,
participantRoot.<Date>get("endTime"),
participantRoot.<Date>get("startTime")
)
);
Expression<Long> count = criteriaBuilder.countDistinct(participantRoot.get("userID"));
reportQuery.select(criteriaBuilder.construct(
UserParticipantCountAndDurationImpl.class,
participantRoot.get("userID").as(UUID.class).alias(USER_ID),
count.as(Long.class).alias(PARTICIPANTS),
sum.as(Long.class).alias(PARTICIPANT_DURATION)
));

有问题的班级

@Data
@NoArgsConstructor
public class UserParticipantCountAndDurationImpl implements UserParticipantCountAndDuration, Serializable {
private UUID userID;
private long participants;
public long participantDuration;
public UserParticipantCountAndDurationImpl(
UUID userID,
long participants,
long participantDuration
) {
this.userID = userID;
this.participants = participants;
this.participantDuration = participantDuration;
}
}

是的,我已经尝试过更改构造函数的签名。在这种情况下,查询将运行,但随后会出现CastException,因为它是java.util.Date

您需要一个表达式,其中包含要从timediff函数中提取的单元的名称

public static class TimeUnitExpression extends BasicFunctionExpression<String> implements Serializable {
public TimeUnitExpression(CriteriaBuilderImpl criteriaBuilder, Class<String> javaType,
String functionName) {
super(criteriaBuilder, javaType, functionName);
}
@Override
public String render(RenderingContext renderingContext) {
return getFunctionName();
}
}

所以你的和表达式变成

Expression<Long> sum = criteriaBuilder.sum(
criteriaBuilder.function(
"TIMEDIFF",
Long.class,
new TimeUnitExpression(null, String.class, "MILLISECOND"),
participantRoot.<Date>get("endTime"),
participantRoot.<Date>get("startTime")
)
);

TIMEDIFF返回日期-时间作为结果,因此它不能被强制转换为Long或double,原始结果中的Sql对象是DateTime,请参阅此。我可以通过使用函数从日期时间中获取分钟来解决这个问题。但我通过获得求和的日期时间的UNIXTIMESTAMP差来解决这个问题。由于UNIXTTIMESTAMP总是,我可以将其强制转换为long或BigInteger

相关内容

  • 没有找到相关文章

最新更新