Zach Cochran
by Zach Cochran
2 min read

Categories

Tags

I was curious just how much different it would be trying to connect a Spring Boot project to a MongoDB database instead of using an SQL database like we did in one of the previous tutorials I wrote about. So I went back to the internet looking for an example of how it’s done with MongoDB, with the goal of connecting to an external DB (something that wasn’t covered in the other lesson).

Turns out that Spring Boot makes it all super easy for you, again with very little effort required of the end user.

The tutorial that I followed can be found here on medium.

For this project, the only required Spring Boot packages were Web and MongoDB. Pretty much the same as in the last tutorial I did, with the exception of switching out MongoDB for SQL.

The process was nearly identical to that we used for a SQL database. We first start by making out model. The model uses the exact same principals, where we’re defining our main key, and then creating a bunch of getters and setters for each of our parameters.

We then move on to creating a repository which is how we tell our application how to relate mongo to our model. From how I understand it, the name of this interface needs to lead with the name of the collection that it will be connecting to, so that the application know where it’s supposed to be talking to. Just like with the SQL app, most of the functionality just works out of the box. The only thing we end up adding is support for finding by an Id.

The last bit is just the controller, but there’s nothing here that’s new. It’s just defining all of our routes and connecting it back to our model and repository.

However, there WAS something interesting about how the author did this (and something I hadn’t seen before). In his implementation, he went ahead and started nesting paths. That’s to say, he’d define a top level /pets path, and then within that class, define even more paths that are related to it.

Previously Id only ever seen defining all of the routes at the top level.

The other thing that was brought up here was the use of @Valid, which will force some level of validation on received data. This is used to compare data from the message body with the format of the data model before trying to post to the db. In order to use it against the message body, you just simply need to define the Model and give a variable for that model:

   @PostMapping("/")
   public Pets createPet(@Valid @RequestBody Pets pets) {
       pets.set_id(ObjectId.get());
       repository.save(pets);
       return pets;
   }

💚