Java
Spring Framework
IllegalArgumentException
Annotations
Exception Handling

java.lang.IllegalArgumentExceptionEither use Param on all parameters except Pageable and Sort typed once, or none at all

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

When developing applications using Spring Data JPA, encountering the exception `java.lang.IllegalArgumentException: Either use @Param on all parameters except Pageable and Sort typed ones, or none at all` can be puzzling, especially for those new to Spring Data custom repositories. This exception is thrown when there's an inconsistency in how method parameters are annotated in Spring Data's repository query methods. This article breaks down the technicalities of this error, providing insights into its causes and solutions, ultimately guiding developers through effective query creation.

Understanding the Exception

What is `IllegalArgumentException`?

The `IllegalArgumentException` in Java signals that a method has received an inappropriate or illegal argument. This falls under unchecked exceptions and can be avoided through careful API usage. In the context of Spring Data repositories, this exception typically points to incorrect use of method parameter annotations.

The Role of `@Param`

In Spring Data JPA, the `@Param` annotation is used to bind method parameters to query parameters in repository methods. It helps to explicitly associate the parameters passed into a repository method with the parameters defined in a query method, especially when using named parameters in JPQL or native SQL queries.

The Error in Context

The error occurs in the following scenario:

  • Your query method has a mix of annotated and non-annotated parameters, excluding parameters of type `Pageable` or `Sort`.
  • Spring Data mandates that you either annotate all applicable parameters with `@Param` or none at all.

Example Scenario

Consider the following JPQL query annotated method:

  • Annotate All Parameters: If using `@Param`, all query method parameters (excluding `Pageable` and `Sort`) should be annotated.
  • No Annotation: Avoid using `@Param` entirely; useful for simple methods where parameter order aligns with query definition.
  • Consistency is Key: Ensure all applicable parameters are consistently annotated with `@Param` or not at all.
  • Exception Avoidance: Avoid mixing annotated and unannotated parameters to prevent `IllegalArgumentException`.
  • Special Parameters: Understand the exception to `Pageable` and `Sort`, which do not require `@Param`.

Course illustration
Course illustration

All Rights Reserved.