Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using RepositoryRestResource annotation to change RESTful endpoint not working

I am new to Spring boot. I was trying to create RESTful web service which also plugs into MongoDB. Everything works fine as the guide explains except for this.

package hello.requests;

import java.util.List;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

import hello.models.CustomerModel;

@RepositoryRestResource(collectionResourceRel = "people", path = "people")
public interface CustomerRepository extends MongoRepository<CustomerModel, String> {

    List<CustomerModel> findByLastName(@Param("name") String name);

}

Here I am trying to change the RESTful endpoint for the repository from the default /customerModels to /people. But when I run this, I get 404 if I try /people but works fine for /customerModels. In a broader sense how does @RepositoryRestResource work? What am I doing wrong here?

like image 557
Codevalley Avatar asked Jul 24 '15 11:07

Codevalley


2 Answers

You can't use slash inside the path attribute, but you can set base path in application.properties:

# DATA REST (RepositoryRestProperties)
spring.data.rest.base-path=/my/base/uri
# Base path to be used by Spring Data REST to expose repository resources.
like image 153
kinjelom Avatar answered Oct 10 '22 22:10

kinjelom


Without seeing your entire configuration it is hard to know exactly what is going on in your situation. However using the latest guide at https://github.com/spring-guides/gs-accessing-data-mongodb.git I am able to get it working by making the following changes:

  • Adding spring-boot-starter-data-rest as a dependency in the POM file.

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-rest</artifactId>
    </dependency>
    
  • Adding this annotation to the CustomerRepository class.

    @RepositoryRestResource(path = "people")
    
  • Setting up getters and setters in the Customer class for the 2 name fields in the constructor to avoid a Jackson serialization error.

Using this when I run the application I am able to access the repository at http://localhost:8080/people. If I remove the annotation then the CustomerRepository is accessed at http://localhost:8080/customers. Let me know if you want me to post a fork on GitHub.

To answer your question about what RepositoryRestResource is that it overrides the attributes for the ResourceMapping that is created by default. It's attributes are used in creating the mapping and change the related return values of the methods on the mapping class. By default Spring Data Rest creates defaults based on the class names of the objects used in the repository definition.

like image 24
Rob Baily Avatar answered Oct 10 '22 23:10

Rob Baily