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:

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

}
[/code]

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

[code language=”bash”]
$ 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."}
[/code]

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:

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

}
[/code]

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:

[code language=”xml” highlight=”16″]
<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>

[/code]

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

2 Comments:

  1. Thank you for sharing excellent informations. Your web-site is very cool. I’m impressed by the details that you have on this site. It reveals how nicely you understand this subject. Bookmarked this website page, will come back for extra articles. You, my pal, ROCK! I found simply the information I already searched all over the place and simply could not come across. What an ideal site.

  2. Its good as your other blog posts : D, regards for putting up. “The rewards for those who persevere far exceed the pain that must precede the victory.” by Ted W. Engstrom.

Leave a Reply

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