Spring JPA获取最大Exec值查询问题(禁用@Query)
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
findFirstto fetch only the top result after sorting - Place all filter conditions before the
OrderByclause - Follow camelCase for
OrderByand the property name (IdExecDesc, notorderbyIdExecDesc) - Remove duplicate
Andkeywords (you hadAndAnd)
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:
First incorrect method:
findFirstfindByIdVersionCierreAndAndValidatedOrderbyIdExecDescAndIdProcessIn- Duplicate
find(should befindFirst, notfindFirstfind) - Misplaced
IdProcessIncondition (all filters must come before sorting) - Incorrect casing for
orderby(should beOrderBy) - Extra
And(should beAndValidated, notAndAndValidated)
- Duplicate
Second incorrect method:
findFirstfindByIdVersionCierreAndAndValidatedAndIdProcessInOrderbyIdExecDesc- Duplicate
find(again,findFirstis correct) - Extra
And(remove one to makeAndValidated) - Incorrect casing for
orderby(needs to beOrderBy)
- Duplicate
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

