Exception: Use @Param for query method parameters, or when on Java 8+ use the javac flag -parameters.; nested exception is java.lang.IllegalStateException:

This exception occurs in a Spring Data JPA repository when using named parameters in a query without properly annotating or providing names for those parameters. Named parameters are identified by a name preceded by a colon (e.g., :paramName) in JPQL or native queries. If the parameter names are not correctly provided or mapped, Spring cannot bind the query parameters.

Causes of the Exception
  1. Missing @Param Annotation: When using named parameters in a query, the corresponding method parameters in the repository interface must be annotated with @Param to specify their names.
  2. Compiled Without -parameters Flag: If you’re using Java 8 or later, the -parameters compiler flag enables Spring to infer parameter names automatically. Without this flag, Spring cannot infer the names, resulting in the exception.

Solution

1. Using @Param Annotation: Add @Param annotations to your repository method parameters, matching the names used in the query.

Example: JPQL Query
@Repository
public interface FlightRepository extends JpaRepository<Flight, Long> {

    @Query("SELECT f FROM Flight f WHERE f.flightNumber = :flightNumber AND f.departureDate = :departureDate")
    List<Flight> findByFlightNumberAndDepartureDate(
        @Param("flightNumber") String flightNumber,
        @Param("departureDate") LocalDate departureDate
    );
}
2. Using the -parameters Compiler Flag:

When using Java 8+ and the -parameters flag, Spring can infer parameter names from the method signature, making @Param annotations optional. How to Enable the Flag:

Maven: Add the following to your pom.xml
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.8.1</version>
    <configuration>
        <compilerArgs>
            <arg>-parameters</arg>
        </compilerArgs>
    </configuration>
</plugin>

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *