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

Spring JPA获取最大Exec值查询问题(禁用@Query)

Fixing Spring JPA Method to Fetch Record with Maximum idExec (No @Query)

I see where you went wrong with your method naming—Spring Data JPA has strict rules for query derivation, and your attempts had syntax issues like duplicate keywords, incorrect casing, and misplaced ordering clauses. Let's fix this step by step:

The Correct Method Name & Repository Setup

The key points to get right:

  • Use findFirst to fetch only the top result after sorting
  • Place all filter conditions before the OrderBy clause
  • Follow camelCase for OrderBy and the property name (IdExecDesc, not orderbyIdExecDesc)
  • Remove duplicate And keywords (you had AndAnd)

Here's the corrected repository interface:

@Repository
public interface DataValidationRepository extends CrudRepository<TpValidaAuto, String> {
    // Original method (returns all matching records)
    List<TpValidaAuto> findByIdVersionCierreAndValidatedAndIdProcessIn(String version, int validated, List<String> process);
    
    // New method to get the record with the highest idExec
    Optional<TpValidaAuto> findFirstByIdVersionCierreAndValidatedAndIdProcessInOrderByIdExecDesc(String version, int validated, List<String> process);
}

Why Your Previous Attempts Failed

Let's break down the issues:

  1. First incorrect method: findFirstfindByIdVersionCierreAndAndValidatedOrderbyIdExecDescAndIdProcessIn

    • Duplicate find (should be findFirst, not findFirstfind)
    • Misplaced IdProcessIn condition (all filters must come before sorting)
    • Incorrect casing for orderby (should be OrderBy)
    • Extra And (should be AndValidated, not AndAndValidated)
  2. Second incorrect method: findFirstfindByIdVersionCierreAndAndValidatedAndIdProcessInOrderbyIdExecDesc

    • Duplicate find (again, findFirst is correct)
    • Extra And (remove one to make AndValidated)
    • Incorrect casing for orderby (needs to be OrderBy)

How to Use the Corrected Method

Call the new method exactly like your original one—it will return the single record matching your filters with the highest idExec value:

Optional<TpValidaAuto> result = dataValidationRepository.findFirstByIdVersionCierreAndValidatedAndIdProcessInOrderByIdExecDesc("1A", 1, Arrays.asList("process1", "process2"));

// Handle the optional safely to avoid NPE
result.ifPresent(record -> {
    // Do something with the record
    System.out.println("Highest idExec record: " + record.getIdExec());
});

Using Optional<TpValidaAuto> is safer than returning a raw TpValidaAuto because it forces you to handle cases where no matching records exist, preventing unexpected null pointer exceptions.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 22:17:27