You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用CriteriaBuilder.max()处理LocalDate时出现类型不匹配错误

解决CriteriaBuilder子查询获取最大LocalDate的类型不匹配问题

问题出在你使用了criteriaBuilder.max()方法——这个方法是专门为数值类型设计的,当传入LocalDate类型的属性时,它会返回Expression<Number>,和你子查询声明的返回类型LocalDate不匹配,因此触发类型错误。

正确的做法是使用criteriaBuilder.greatest()方法,它支持所有实现了Comparable接口的类型(包括LocalDate),能正确返回对应类型的表达式。同时注意,子查询需要创建自己的Root实例,不要复用父查询的root,避免查询范围错误。

修正后的代码如下:

Subquery<LocalDate> subQuery = criteriaQuery.subquery(LocalDate.class);
Root<YourEntity> subRoot = subQuery.from(YourEntity.class); // 替换为你的实体类
subQuery.select(criteriaBuilder.greatest(subRoot.get("date")));

内容的提问来源于stack exchange,提问作者Vishal Naik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 02:21:59