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

Spring Data JPA自定义查询报Illegal attempt to dereference错误如何解决?

问题修复方案

错误根因

你定义的查询方法findByCocIdAndMonth_Year意图提取month字段的年份值做查询,但Spring Data JPA的方法名属性解析规则中,仅关联实体类型支持通过下划线(对应属性路径的.)访问下一级属性,而ZonedDateTime属于JPA原生支持的基本时间类型,并非你项目中定义的关联实体,因此JPA尝试将month作为关联实体解析其year属性时,就会抛出路径引用失败的错误。

可选择的修复方案

方案1:使用@Query自定义JPQL查询(最推荐,通用性强)

直接在Repository方法上加@Query注解,调用JPQL内置的时间函数提取年份:

@Repository
public interface LoremRepository extends JpaRepository<LoremEntity, Long> {
    @Query("SELECT l FROM LoremEntity l WHERE l.cocId = :cocId AND YEAR(l.month) = :year")
    List<LoremEntity> findByCocIdAndMonthYear(Long cocId, int year);
}

绝大多数主流关系型数据库都支持YEAR()函数提取时间字段的年份值,适配性很高。

方案2:传入时间范围做范围查询(无需写自定义SQL)

调整方法逻辑,传入目标年份的起止时间作为查询参数,用JPA原生的Between关键字查询:

@Repository
public interface LoremRepository extends JpaRepository<LoremEntity, Long> {
    List<LoremEntity> findByCocIdAndMonthBetween(Long cocId, ZonedDateTime startOfYear, ZonedDateTime endOfYear);
}

调用方法前自行构造对应年份的起止时间即可,示例如下:

// 构造2024年的起止时间示例
ZonedDateTime startOfYear = ZonedDateTime.of(2024, 1, 1, 0, 0, 0, 0, ZoneId.systemDefault());
ZonedDateTime endOfYear = ZonedDateTime.of(2025, 1, 1, 0, 0, 0, 0, ZoneId.systemDefault()).minusNanos(1);
List<LoremEntity> result = loremRepository.findByCocIdAndMonthBetween(cocId, startOfYear, endOfYear);

内容的提问来源于stack exchange,提问作者Tung Vo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 00:21:04