Building a Full-Stack CRUD App with Spring Boot, Next.js, and MongoDB


To create a CRUD application using Spring Boot and Next.js with MongoDB, you'll need to build the backend with Spring Boot to handle the database operations and the frontend with Next.js for the UI. Here's a step-by-step guide to set this up:

1. Set up Spring Boot Backend (Spring Boot + MongoDB)

Dependencies (pom.xml)

First, add the necessary dependencies to your pom.xml file.

<dependencies>
    <!-- Spring Boot Starter Web -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    
    <!-- Spring Boot Starter Data MongoDB -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-mongodb</artifactId>
    </dependency>
    
    <!-- Spring Boot Starter Test (Optional) -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

Application Properties (application.properties)

Configure your MongoDB connection details in src/main/resources/application.properties:

spring.data.mongodb.uri=mongodb://localhost:27017/mydatabase

MongoDB Model

Create a model class that maps to a MongoDB document. For example, a simple Item model:

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document
public class Item {
    @Id
    private String id;
    private String name;
    private String description;

    // Getters and Setters
}

Repository Layer

Create a repository interface extending MongoRepository to handle CRUD operations:

import org.springframework.data.mongodb.repository.MongoRepository;

public interface ItemRepository extends MongoRepository<Item, String> {
}

Service Layer

Create a service class to encapsulate the CRUD logic:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class ItemService {

    @Autowired
    private ItemRepository itemRepository;

    public List<Item> getAllItems() {
        return itemRepository.findAll();
    }

    public Optional<Item> getItemById(String id) {
        return itemRepository.findById(id);
    }

    public Item addItem(Item item) {
        return itemRepository.save(item);
    }

    public Item updateItem(String id, Item item) {
        item.setId(id);
        return itemRepository.save(item);
    }

    public void deleteItem(String id) {
        itemRepository.deleteById(id);
    }
}

Controller Layer

Create a controller to handle HTTP requests:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/items")
public class ItemController {

    @Autowired
    private ItemService itemService;

    @GetMapping
    public List<Item> getAllItems() {
        return itemService.getAllItems();
    }

    @GetMapping("/{id}")
    public Optional<Item> getItemById(@PathVariable String id) {
        return itemService.getItemById(id);
    }

    @PostMapping
    public Item createItem(@RequestBody Item item) {
        return itemService.addItem(item);
    }

    @PutMapping("/{id}")
    public Item updateItem(@PathVariable String id, @RequestBody Item item) {
        return itemService.updateItem(id, item);
    }

    @DeleteMapping("/{id}")
    public void deleteItem(@PathVariable String id) {
        itemService.deleteItem(id);
    }
}

Now, your Spring Boot application will expose CRUD endpoints for items.

2. Set up Next.js Frontend

Install Next.js

If you haven't already, create a Next.js app:

npx create-next-app@latest my-next-app
cd my-next-app
npm install

Install Axios for API calls

To make HTTP requests to the Spring Boot backend, install Axios:

npm install axios

Create API Utility (Axios)

Create a utility file utils/api.js to handle API requests to your Spring Boot backend:

import axios from 'axios';

const api = axios.create({
  baseURL: 'http://localhost:8080/api/items',
});

export const getItems = async () => {
  const response = await api.get('/');
  return response.data;
};

export const createItem = async (item) => {
  const response = await api.post('/', item);
  return response.data;
};

export const updateItem = async (id, item) => {
  const response = await api.put(`/${id}`, item);
  return response.data;
};

export const deleteItem = async (id) => {
  await api.delete(`/${id}`);
};

Create Pages for CRUD Operations

Now, you can create pages in Next.js to perform CRUD operations.

  1. Display All Items: pages/index.js
import { useEffect, useState } from 'react';
import { getItems } from '../utils/api';

export default function Home() {
  const [items, setItems] = useState([]);

  useEffect(() => {
    const fetchItems = async () => {
      const items = await getItems();
      setItems(items);
    };
    fetchItems();
  }, []);

  return (
    <div>
      <h1>Items List</h1>
      <ul>
        {items.map((item) => (
          <li key={item.id}>
            {item.name} - {item.description}
          </li>
        ))}
      </ul>
    </div>
  );
}
  1. Create Item: pages/create.js
import { useState } from 'react';
import { createItem } from '../utils/api';

export default function Create() {
  const [name, setName] = useState('');
  const [description, setDescription] = useState('');

  const handleSubmit = async (e) => {
    e.preventDefault();
    await createItem({ name, description });
    alert('Item created successfully!');
  };

  return (
    <div>
      <h1>Create Item</h1>
      <form onSubmit={handleSubmit}>
        <input
          type="text"
          placeholder="Name"
          value={name}
          onChange={(e) => setName(e.target.value)}
        />
        <input
          type="text"
          placeholder="Description"
          value={description}
          onChange={(e) => setDescription(e.target.value)}
        />
        <button type="submit">Create</button>
      </form>
    </div>
  );
}

Set up the Backend and Frontend

  1. Start the Spring Boot backend:
mvn spring-boot:run
  1. Start the Next.js frontend:
npm run dev

Now, your app should be running at http://localhost:3000, and you can perform CRUD operations on MongoDB using the Spring Boot backend.

This setup will give you a basic CRUD app with Next.js as the frontend and Spring Boot as the backend, interacting with MongoDB.

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete