Spring Boot, Spring Data REST and Query Parameters

I have Spring Data REST repository that takes query parameters. It uses a PagingAndSortingRepository and looks like this:

@RepositoryRestResource
@CrossOrigin(origins = "http://localhost:8000")
public interface IRestaurantRepository extends PagingAndSortingRepository<Restaurant, Long> {
	public Page<Restaurant> findByNameContaining(String name, Pageable pageable);

}

You would get an error if you were to execute the search command that is created for you with cURL.

$ curl -X GET http://localhost:8181/restaurants/search/findByNameContaining?name=Foo
{"cause":null,"message":"Unable to detect parameter names for query method com.coysoft.wingspecial.repository.IRestaurantRepository.findByNameContaining! Use @Param or compile with -parameters on JDK 8."}

The error is pretty useful. It gives us two options for being able to use query parameters. The first is straightforward. Just modify the code like so:

@RepositoryRestResource
@CrossOrigin(origins = "http://localhost:8000")
public interface IRestaurantRepository extends PagingAndSortingRepository<Restaurant, Long> {
	public Page<Restaurant> findByNameContaining(@Param("name") String name, Pageable pageable);

}

With this modification you’ll be able to get results. The second option involves modifying your build process. In my case, I am using Maven and I am in fact using Java 8. Therefore, I can modify the pom.xml to use this:

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.3</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
					<fork>true</fork>
					<compilerArgs>
						<arg>-parameters</arg>
					</compilerArgs>
				</configuration>
			</plugin>
		</plugins>
		<finalName>ROOT</finalName>
	</build>

Both work the same for me. Using @Param is more backwards compatible and verbose, but using -parameters would work across the board.

One Comment:

  1. Tomasz Krzysztof

    Hi Kevin,

    Did you encountered any explicit info about a need to map query parameters in the documentation?
    I couldn’t find any explanation for this.

    Godspeed

Leave a Reply

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