javaspringrestjpaspring-data

Implementing custom methods of Spring Data repository and exposing them through REST


I'm trying to add custom methods to my Spring Data repository PersonRepository as described in 1.3 Custom implementations for Spring Data repositories and exposing these method through REST. The initial code is from Accessing JPA Data with REST sample, here is the code for added/modified classes:

interface PersonRepositoryCustom {
  List<Person> findByFistName(String name);
}

class PersonRepositoryImpl implements PersonRepositoryCustom, InitializingBean {
  @Override
  public void afterPropertiesSet() throws Exception {
    // initialization here
  }
  @Override
  public List<Person> findByFistName(String name) {
    // find the list of persons with the given firstname
  }
}

@RepositoryRestResource(collectionResourceRel = "people", path = "people")
public interface PersonRepository extends PagingAndSortingRepository<Person, Long> {
  List<Person> findByLastName(@Param("name") String name);  
}

When I run the application and visit http://localhost:8080/portfolio/search/, I get the following response body:

{
  "_links" : {
    "findByLastName" : {
      "href" : "http://localhost:8080/people/search/findByLastName{?name}",
      "templated" : true
     }
  }
}

Why findByFirstName is not exposed even if it is available in the PersonRepository interface?

Also, is there a way to dynamically/programmatically add respositories to be exposed via REST?


Solution

  • The reason these methods are not exposed is that you're basically free to implement whatever you want in custom repository methods and thus it's impossible to reason about the correct HTTP method to support for that particular resource.

    In your case it might be fine to use a plain GET, in other cases it might have to be a POST as the execution of the method has side effects.

    The current solution for this is to craft a custom controller to invoke the repository method.