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

Spring Data JPA:如何根据带下划线的参数test_no查询数据

解决Spring Data JPA中Log模型findBy查询方法的命名问题

你遇到的这些报错都是因为Spring Data JPA的方法命名规则和你的实体字段名不匹配导致的,咱们一步步来解决:

问题根源

你的Log实体类里的字段是test_no(下划线分隔命名),而Spring Data JPA在解析findByXXX这类派生查询方法时,会遵循特定的命名规则来匹配实体属性:

  • 方法名中的驼峰部分会被自动转换为下划线分隔的字段名(比如TestNo → test_no)
  • 如果直接写test或者testno,Spring Data JPA会去寻找对应的test或testno字段,自然找不到你实际的test_no

正确的方法签名

你需要按照驼峰命名规则来对应下划线字段,正确的方法名应该是findByTestNo,示例如下:

public interface LogRepository extends JpaRepository<Log, Long> {
    // 单个结果
    Log findByTestNo(String testNo);
    
    // 多个结果(如果可能存在多条匹配数据)
    List<Log> findByTestNo(String testNo);
}

替代方案:使用@Query注解

如果觉得派生查询的命名规则容易搞混,也可以直接用@Query注解手动指定查询语句,这样更直观:

import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

public interface LogRepository extends JpaRepository<Log, Long> {
    @Query("SELECT l FROM Log l WHERE l.test_no = :testNo")
    Log findByTestNo(@Param("testNo") String testNo);
}

为什么之前的写法报错?

  • Invalid delivery query! No property test found in type Log!:因为你写了类似findByTest()的方法,Spring Data JPA会去匹配实体里的test字段,但你的字段是test_no,所以找不到。
  • Invalid derived query! No property testno found for type Log! Did you mean 'test_no'?:因为你写了findByTestno(),这里没有用驼峰区分,Spring Data JPA识别成要找testno字段,而你的字段是带下划线的test_no,所以给出了提示。

内容的提问来源于stack exchange,提问作者Carlos Vázquez Losada

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 03:38:44