MongoDb with Spring Data

Using spring-data to access MongoDB in Java is quite interesting since the primary goal of Spring Data project is to make it easier to use and it does 🙂

Maven configuration.

That’s the configuration that I used for this simple sample. Notice that I used maven-assembly-plugin do create a fat jar and execute it as a standalone app, may you prefer using something fancy like Spring Boot.


Spring configuration

Next, let’s create the files that will compose the spring configurations, in this case, let’s create them into “src/main/resources”.




Now a really simple model with just an Id and a Title.

OBS : @Data is a Lombook annotation.


Spring Service


Spring Repository

This is a good one, since Spring offers default implementations for CrudRepository like SimpleMongoRepository to perform basic operations (even those not so basic), it’s not necessary to write anything, just create an interface that extends CrudRepository.

That’s it, this is our CRUD.



Observe that I’m just saving here but you can try any other operations available. If you want to learn more and try something else you can check the documentation.

the User Guide
the JavaDocs
the home page of Spring Data MongoDB

Leave a Reply