Skip to content
Advertisement

Spring Boot + MongoDB Id query

I have a Spring Boot application combined with MongoDB as the persistance layer. I have the following structure:

public class Resource {

@Id
public String Id;
...
}

I also have a ResourceRepository:

@RepositoryRestResource(collectionResourceRel = "resources", path = "resources")
public interface ResourceRepository extends MongoRepository<Resource, String> {
     Resource findById(@Param("Id")String Id);
}

I found online that a way to have the id property returned in the JSON when you perform a GET request like http://localhost:8080/resources/ is to change the id property to Id (uppercase i). Indeed, if the property is lowercase, I don’t get back an id field but if I change it to uppercase then I get it. For a reason, I need to get back the id property so I used the uppercase i. So far, so good.

However, when I tried to execute the query findById included in my repository I get an exception:

org.springframework.data.mapping.context.InvalidPersistentPropertyPath: No property id found on app.model.Resource!

If I change the Id property to id (lowercase i) I can execute successfully the /resources/search/findById?id=… GET request.

I tried creating a custom controller with a query that finds and returns a Resource based on the id that is given:

@Controller
@RequestMapping("/resource")
public class ResourceController {

    @Autowired
    MongoOperations mongoOperations;

    @RequestMapping(value="/findById/{resourceId}/", method= RequestMethod.GET)
    @ResponseBody
    public Resource findByResourceId(@PathVariable("resourceId") String resourceId) {
        Resource resource = mongoOperations.findOne(query(Criteria.where("Id").is(resourceId)), Resource.class,"DOJ");
    }
}

but I receive the same error:

org.springframework.data.mapping.context.InvalidPersistentPropertyPath: No property id found on app.model.Resource!

Any idea on how to both have the id property displyed in the JSon and be able to findById?

Advertisement

Answer

Well, I found the answer myself. Switch back to lowercase id so findById works and add the following class to the project:

@Configuration
public class SpringDataRestConfiguration extends RepositoryRestConfigurerAdapter  {

    @Override
    public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
        config.exposeIdsFor(Resource.class);
    }
}

As the name of the method suggests, this configuration makes Resource class objects to expose their ids in JSON.

UPDATE: If you are using the latest or relatively latest version of spring-boot, the RepositoryRestConfigurerAdapter class has been deprecated, and the java-doc suggests to use the interface RepositoryRestConfigurer directly.

So your code should look like this:

@Configuration
public class SpringDataRestConfiguration implements RepositoryRestConfigurer  
...
Advertisement