avatarMaleesha Kumarasinghe

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

6501

Abstract

This connection string will allow your Spring Boot application to communicate with the MongoDB database.</p><h2 id="a856">Step 4: Create a Simple CRUD Application with MongoDB</h2><p id="032a">Now that your project is connected to the database, let’s implement a simple CRUD (Create, Read, Update, Delete) application. Unlike relational databases, non-relational databases like MongoDB store data in flexible formats, such as key-value pairs, documents, columns, or graphs.</p><p id="55e1">Here’s the folder structure we’ll use:</p><ol><li><b>Controller Package</b>: Create a <code>UserController</code> class to handle HTTP requests.</li><li><b>Model Package</b>: Create a <code>User</code> class representing the MongoDB entity.</li><li><b>Repository Package</b>: Create a <code>UserRepo</code> interface for repository operations.</li><li><b>Service Package</b>: Create a <code>UserService</code> class for business logic.</li><li><b>Service Implementation Package</b>: Implement the service logic in this layer.</li></ol><figure id="cec7"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*dXFcXMf6tX6yDpxjNDR3bQ.png"><figcaption></figcaption></figure><h2 id="dbd6">Key Annotations in Spring Boot with MongoDB</h2><p id="7bf5">Before moving forward, it’s important to understand some key annotations that simplify development in Spring Boot:</p><ul><li><code>@Id</code>: Indicates the primary key of the entity (mandatory with <code>@Entity</code>).</li><li><code>@Autowired</code>: Enables dependency injection. Spring Boot automatically provides the necessary dependencies.</li><li><code>@GetMapping</code>, <code>@PostMapping</code>, <code>@PutMapping</code>, <code>@DeleteMapping</code>: These annotations handle HTTP request methods for RESTful APIs.</li><li><code>@RestController</code>: Combines <code>@Controller</code> and <code>@ResponseBody</code>, used for handling RESTful requests.</li><li><code>@RequestMapping</code>: Maps HTTP requests to handler methods in the controller.</li><li><code>@Service</code>: Indicates that a class contains business logic.</li><li><code>@Getter</code> and <code>@Setter</code>: Lombok annotations to generate getter and setter methods.</li><li><code>@Document</code>: Specifies the MongoDB document name.</li><li><code>@RequestBody</code>: Used to map the HTTP request body to a Java object.</li><li><code>@PathVariable</code>: Used to extract values from URI templates.</li></ul><h2 id="4f3d">Step 4: Create the Model Class</h2><p id="210e">Create the model class for <code>User</code>, which will represent the MongoDB document.</p><div id="ab92"><pre><span class="hljs-meta">@Getter</span> <span class="hljs-meta">@Setter</span> <span class="hljs-meta">@Document(collection = "users")</span> <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">userModel</span> {

<span class="hljs-meta">@Id</span>
<span class="hljs-keyword">private</span> String id;
<span class="hljs-keyword">private</span> String username;
<span class="hljs-keyword">private</span> String email;
<span class="hljs-keyword">private</span> <span class="hljs-type">int</span> age;
<span class="hljs-keyword">private</span> String mobileNumber;

}</pre></div><h2 id="7be4">Step 5: Create the Repository</h2><p id="54b4">Next, create a repository interface that extends <code>MongoRepository</code> to handle data access.</p><div id="9070"><pre><span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title class_">userRepository</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_">MongoRepository</span><userModel, String> { }</pre></div><h2 id="b424">Step 6: Create the Service and Service Implementation Layers</h2><p id="5841">The service layer handles business logic, while the repository is used for data access. Implement the CRUD operations here.</p><div id="9bde"><pre><span class="hljs-meta">@Service</span> <span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title class_">userService</span> {

<span class="hljs-keyword">public</span> userModel <span class="hljs-title function_">saveUser</span><span class="hljs-params">(userModel user)</span>;
<span class="hljs-keyword">public</span> Optional&lt;userModel&gt; <span class="hljs-title function_">getUserById</span><span class="hljs-params">(String id)</span>;
<span class="hljs-keyword">public</span> List&lt;userModel&gt; <span class="hljs-title function_">getUsers</span><span class="hljs-params">(userModel user)</span>;
<span class="hljs-keyword">public</span> String <span class="hljs-title function_">deleteUserById</span><span class="hljs-params">(String id)</span>;
<span class="hljs-keyword">public</span> userModel <span class="hljs-title function_">updateUserById</span><span class="hljs-params">(String id, userModel user)</span>;

}</pre></div><div id="e955"><pre><span class="hljs-meta">@Component</span> <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">userServiceImpl</span> <span class="hljs-keyword">implements</span> <span class="hljs-title class_">userService</span> {

<span class="hljs-meta">@Autowired</span>
<span class="hljs-keyword">private</span> userRepository userRepo;

<span class="hljs-meta">@Override</span>
<span class="hljs-keyword">public</span> userModel <span class="hljs-title function_">saveUser</span><span class="hljs-params">(userModel user)</span> {
    <span class="hljs-keyword">return</span> userRepo.save(user);
}

<span class="hljs-meta">@Override</span>
<span class="hljs-keyword">public</span> Optional&lt;userModel&gt; <span class="hljs-title function_">getUserById</span><span class="hljs-params">(String id)</span> {
    <span class="hljs-keyword">return</span> userRepo.findById(id);
}

<span class="hljs-meta">@Override</span>
<span class="hljs-keyword">public</span> List&lt;userModel&gt; <span class="hljs-title function_">getUsers</span><span class="hljs-params">(userModel user)</span> {
    <span class="hljs-keyword">return</span> userRepo.findAll();
}

<span class="hljs-meta">@Override</span>
<span class="hljs-keyword">public</span> String <span class="hljs-title function_">deleteUserById</span><span class="hljs-params">(String id)</span> {
    Optional&lt;userMode

Options

l> user = userRepo.findById(id); <span class="hljs-keyword">if</span>(user.isPresent()) { userRepo.deleteById(id); <span class="hljs-keyword">return</span> <span class="hljs-string">"User deleted"</span>; }<span class="hljs-keyword">else</span> { <span class="hljs-keyword">return</span> <span class="hljs-string">"User not found"</span>; } }

<span class="hljs-meta">@Override</span>
<span class="hljs-keyword">public</span> userModel <span class="hljs-title function_">updateUserById</span><span class="hljs-params">(String id, userModel user)</span> {
    Optional&lt;userModel&gt; updateUser = userRepo.findById(id);

    <span class="hljs-keyword">if</span>(updateUser.isPresent()) {
        <span class="hljs-type">userModel</span> <span class="hljs-variable">newUser</span> <span class="hljs-operator">=</span> updateUser.get();

        newUser.setUsername(user.getUsername());
        newUser.setEmail(user.getEmail());
        newUser.setAge(user.getAge());
        newUser.setMobileNumber(user.getMobileNumber());
        <span class="hljs-keyword">return</span> userRepo.save(newUser);
    }<span class="hljs-keyword">else</span>{
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">RuntimeException</span>(<span class="hljs-string">"User not found with id: "</span> + id);
    }
}

}</pre></div><h2 id="1c20">Step 6: Create the Controller class</h2><p id="1e46">The controller layer in a Spring Boot application handles HTTP requests and responses, bridging the gap between the client and the service layer.</p><div id="854a"><pre><span class="hljs-meta">@RestController</span> <span class="hljs-meta">@RequestMapping("/api/user")</span> <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">userController</span> {

<span class="hljs-meta">@Autowired</span>
<span class="hljs-keyword">private</span> userService userservice;

<span class="hljs-meta">@PostMapping(value = "/save")</span>
<span class="hljs-keyword">public</span> userModel <span class="hljs-title function_">save</span><span class="hljs-params">(<span class="hljs-meta">@RequestBody</span> userModel user)</span>{
    <span class="hljs-keyword">return</span> userservice.saveUser(user);
}

<span class="hljs-meta">@GetMapping(value= "/get-user/{id}")</span>
<span class="hljs-keyword">public</span> Optional&lt;userModel&gt; <span class="hljs-title function_">getUser</span><span class="hljs-params">(<span class="hljs-meta">@PathVariable</span> String id)</span>{
    <span class="hljs-keyword">return</span> userservice.getUserById(id);
}

<span class="hljs-meta">@GetMapping(value="/users")</span>
<span class="hljs-keyword">public</span> List&lt;userModel&gt; <span class="hljs-title function_">getAllUsers</span><span class="hljs-params">(userModel users)</span>{
    <span class="hljs-keyword">return</span> userservice.getUsers(users);
}

<span class="hljs-meta">@DeleteMapping(value="/delete/{id}")</span>
<span class="hljs-keyword">public</span> String <span class="hljs-title function_">deleteUser</span><span class="hljs-params">(<span class="hljs-meta">@PathVariable</span> String id)</span>{
    <span class="hljs-keyword">return</span> userservice.deleteUserById(id);
}

<span class="hljs-meta">@PutMapping(value = "/update/{id}")</span>
<span class="hljs-keyword">public</span> userModel <span class="hljs-title function_">updateUser</span><span class="hljs-params">(<span class="hljs-meta">@PathVariable</span> String id, <span class="hljs-meta">@RequestBody</span> userModel user)</span>{
    <span class="hljs-keyword">return</span> userservice.updateUserById(id, user);
}

}</pre></div><h2 id="8f24">Step 7: Testing with Postman</h2><p id="e0b7">Now that the CRUD operations are set up, you can use Postman to test them by sending POST, GET, PUT, and DELETE requests to the application.</p><p id="d877">When creating a request in Postman, first select the request type, then enter the localhost URL and specify the appropriate endpoint mapping. Once you send the request successfully, you should see a 200 OK message in the console, indicating that the data has been processed correctly.</p><ol><li>Insert User</li></ol><figure id="13e6"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*ZGKndhISAfzYDSC0nYtQ1A.png"><figcaption></figcaption></figure><p id="4696">2. Get All Users</p><figure id="ae5e"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*DfI-l1aVXjbEW5z0t9qkag.png"><figcaption></figcaption></figure><p id="a2e9">3. Get user by Id</p><figure id="9f68"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*ojRneMeWY_GYT9u6dMqY2w.png"><figcaption></figcaption></figure><p id="eef1">4. Delete User</p><figure id="5b11"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*Eq3er1OxZz3mQ5VYw6CDMQ.png"><figcaption></figcaption></figure><p id="85f4">5. Update User.</p><figure id="2d32"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*idQSkfBvSVU9sXzUPD3oVQ.png"><figcaption></figcaption></figure><h2 id="1c52">Step 8: Check the MongoDB</h2><p id="9695">if you have correctly done the implementation you can see there is a collection in the MongoDB with you given name and a document as user.</p><figure id="e41d"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*TBnW9bDi9vCRC6sEbJrqrQ.jpeg"><figcaption></figcaption></figure><p id="3554">Done !</p><p id="d83a">In this article, we explored how to create a complete CRUD operation using Spring Boot and MongoDB, covering everything from setting up your project to implementing and testing your APIs. We hope this guide has provided you with valuable insights and practical experience in building robust applications with Spring Boot. 🚀</p><p id="e5ca">Thank you for joining us on this journey. We look forward to seeing you in our next article, I will create a docker image for this simple project. Until then, happy learning, and stay tuned for more updates! 📚✨</p><p id="7cf2">Goodbye, and best wishes on your coding adventures! 👋💻</p><p id="a1d9">Sample Code : <a href="https://github.com/KMaleesha/SpringBoot-with-mongoDB.git">https://github.com/KMaleesha/SpringBoot-with-mongoDB.git</a></p></article></body>

Let’s create a simple CRUD application using Spring Boot with MongoDB

In a previous article, I described what Spring Boot is and how to connect it with an SQL database. For a detailed introduction to Spring Boot, you can refer to my earlier article.

What is Spring Boot, and Why MongoDB?

Spring Boot is a project built on the Spring Framework, designed to simplify application development by eliminating the need for extensive configuration. With embedded servers, simplified setup, and production-ready features, it allows developers to focus on business logic without worrying about low-level configuration.

While SQL databases have traditionally been the go-to for many applications, NoSQL databases like MongoDB offer significant advantages for modern applications. MongoDB is a document-based, distributed database that stores data in a JSON-like format called BSON. Here are a few reasons why MongoDB might be a good choice for your Spring Boot application:

  • Schema-less Data Model: MongoDB allows dynamic schemas, providing flexibility to store various types of data without requiring a rigid structure.
  • Scalability: It is horizontally scalable, making it a great choice for applications that expect rapid growth and high traffic.
  • High Performance: MongoDB supports fast read and write operations, making it suitable for real-time data processing.
  • Easy Integration with Spring Boot: Spring Boot provides native support for MongoDB through the Spring Data MongoDB module, enabling seamless repository management, queries, and aggregation functions.

Step 1: Create a Cluster in MongoDB Atlas

  1. Create an account on MongoDB Atlas.
  2. After logging in, click on the “Create a Cluster” tab in the overview.

3. Select the free MongoDB cloud environment.

4. Name your cluster.

5. Choose a cloud provider.

6. Select a region (you can choose the nearest one for better performance).

7. (Optional) Add tags, though they are not necessary here.

8. Click “Create Deployment.”

9. Once the cluster is created, connect to it.

10. Set up a database user by providing a username and password.

11. In the second step, choose a connection method.

12. Select “Drivers.”

13. Choose the Java driver.

14. Copy the connection string and save it in a notepad. This will be needed later when connecting the database to your application.

15. Your cluster is now ready, and you can see a sample database with collections. You can remove the sample database if you don’t need it.

Step 2: Create the Spring Boot Project in IntelliJ IDEA

  1. Open IntelliJ IDEA.
  2. Click on “New Project.”
  3. Select “Spring Initializr.”
  4. Configure your project settings:
  • Language: Java
  • Project SDK: Select the installed JDK version.
  • Project Metadata: Provide a project name (e.g., demo).
  • Packaging: Jar
  • Java Version: Choose the version you are using (e.g., Java 17).

5. Add the following dependencies:

  • Spring Web
  • Spring Data MongoDB
  • Lombok

6. Click “Finish” to create the project. IntelliJ IDEA will generate the project structure and download the necessary dependencies.

7. To verify that the project is set up correctly, navigate to the main class annotated with @SpringBootApplication in the src/main/java directory.

8. Right-click on the main class and select “Run.”

9. Check the console output to ensure the application is running, and the embedded Tomcat server has started.

Step 3: Configure the Database Connection

Now, configure the MongoDB database connection by updating the application.properties file in the src/main/resources directory. Add the following configurations:

spring.application.name=SpringWithMongo
spring.data.mongodb.uri=mongodb+srv://<username>:<password>@cluster0.xosqt.mongodb.net/<databasename>?retryWrites=true&w=majority&appName=Cluster0

Replace <username>, <password>, and <databasename> with your MongoDB credentials. This connection string will allow your Spring Boot application to communicate with the MongoDB database.

Step 4: Create a Simple CRUD Application with MongoDB

Now that your project is connected to the database, let’s implement a simple CRUD (Create, Read, Update, Delete) application. Unlike relational databases, non-relational databases like MongoDB store data in flexible formats, such as key-value pairs, documents, columns, or graphs.

Here’s the folder structure we’ll use:

  1. Controller Package: Create a UserController class to handle HTTP requests.
  2. Model Package: Create a User class representing the MongoDB entity.
  3. Repository Package: Create a UserRepo interface for repository operations.
  4. Service Package: Create a UserService class for business logic.
  5. Service Implementation Package: Implement the service logic in this layer.

Key Annotations in Spring Boot with MongoDB

Before moving forward, it’s important to understand some key annotations that simplify development in Spring Boot:

  • @Id: Indicates the primary key of the entity (mandatory with @Entity).
  • @Autowired: Enables dependency injection. Spring Boot automatically provides the necessary dependencies.
  • @GetMapping, @PostMapping, @PutMapping, @DeleteMapping: These annotations handle HTTP request methods for RESTful APIs.
  • @RestController: Combines @Controller and @ResponseBody, used for handling RESTful requests.
  • @RequestMapping: Maps HTTP requests to handler methods in the controller.
  • @Service: Indicates that a class contains business logic.
  • @Getter and @Setter: Lombok annotations to generate getter and setter methods.
  • @Document: Specifies the MongoDB document name.
  • @RequestBody: Used to map the HTTP request body to a Java object.
  • @PathVariable: Used to extract values from URI templates.

Step 4: Create the Model Class

Create the model class for User, which will represent the MongoDB document.

@Getter
@Setter
@Document(collection = "users")
public class userModel {

    @Id
    private String id;
    private String username;
    private String email;
    private int age;
    private String mobileNumber;

}

Step 5: Create the Repository

Next, create a repository interface that extends MongoRepository to handle data access.

public interface userRepository extends MongoRepository<userModel, String> {
}

Step 6: Create the Service and Service Implementation Layers

The service layer handles business logic, while the repository is used for data access. Implement the CRUD operations here.

@Service
public interface userService {

    public userModel saveUser(userModel user);
    public Optional<userModel> getUserById(String id);
    public List<userModel> getUsers(userModel user);
    public String deleteUserById(String id);
    public userModel updateUserById(String id, userModel user);
}
@Component
public class userServiceImpl implements userService {

    @Autowired
    private userRepository userRepo;

    @Override
    public userModel saveUser(userModel user) {
        return userRepo.save(user);
    }

    @Override
    public Optional<userModel> getUserById(String id) {
        return userRepo.findById(id);
    }

    @Override
    public List<userModel> getUsers(userModel user) {
        return userRepo.findAll();
    }

    @Override
    public String deleteUserById(String id) {
        Optional<userModel> user = userRepo.findById(id);
        if(user.isPresent()) {
            userRepo.deleteById(id);
            return "User deleted";
        }else {
            return "User not found";
        }
    }

    @Override
    public userModel updateUserById(String id, userModel user) {
        Optional<userModel> updateUser = userRepo.findById(id);

        if(updateUser.isPresent()) {
            userModel newUser = updateUser.get();

            newUser.setUsername(user.getUsername());
            newUser.setEmail(user.getEmail());
            newUser.setAge(user.getAge());
            newUser.setMobileNumber(user.getMobileNumber());
            return userRepo.save(newUser);
        }else{
            throw new RuntimeException("User not found with id: " + id);
        }
    }
}

Step 6: Create the Controller class

The controller layer in a Spring Boot application handles HTTP requests and responses, bridging the gap between the client and the service layer.

@RestController
@RequestMapping("/api/user")
public class userController {

    @Autowired
    private userService userservice;

    @PostMapping(value = "/save")
    public userModel save(@RequestBody userModel user){
        return userservice.saveUser(user);
    }

    @GetMapping(value= "/get-user/{id}")
    public Optional<userModel> getUser(@PathVariable String id){
        return userservice.getUserById(id);
    }

    @GetMapping(value="/users")
    public List<userModel> getAllUsers(userModel users){
        return userservice.getUsers(users);
    }

    @DeleteMapping(value="/delete/{id}")
    public String deleteUser(@PathVariable String id){
        return userservice.deleteUserById(id);
    }

    @PutMapping(value = "/update/{id}")
    public userModel updateUser(@PathVariable String id, @RequestBody userModel user){
        return userservice.updateUserById(id, user);
    }

}

Step 7: Testing with Postman

Now that the CRUD operations are set up, you can use Postman to test them by sending POST, GET, PUT, and DELETE requests to the application.

When creating a request in Postman, first select the request type, then enter the localhost URL and specify the appropriate endpoint mapping. Once you send the request successfully, you should see a `200 OK` message in the console, indicating that the data has been processed correctly.

  1. Insert User

2. Get All Users

3. Get user by Id

4. Delete User

5. Update User.

Step 8: Check the MongoDB

if you have correctly done the implementation you can see there is a collection in the MongoDB with you given name and a document as user.

Done !

In this article, we explored how to create a complete CRUD operation using Spring Boot and MongoDB, covering everything from setting up your project to implementing and testing your APIs. We hope this guide has provided you with valuable insights and practical experience in building robust applications with Spring Boot. 🚀

Thank you for joining us on this journey. We look forward to seeing you in our next article, I will create a docker image for this simple project. Until then, happy learning, and stay tuned for more updates! 📚✨

Goodbye, and best wishes on your coding adventures! 👋💻

Sample Code : https://github.com/KMaleesha/SpringBoot-with-mongoDB.git

Spring Boot
Mongodb
Java
Programming
Crud Operations
Recommended from ReadMedium