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:

JavaScript

I also have a ResourceRepository:

JavaScript

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:

JavaScript

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:

JavaScript

but I receive the same error:

JavaScript

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:

JavaScript

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:

JavaScript
Advertisement