Building a Spring Boot MVC Application with Database Integration

In this blog, we'll take the previous Spring Boot MVC application a step further by integrating a database. We'll create a simple web application that allows users to add, list, and view items stored in a relational database (H2 in-memory database in this case). Follow along to learn how to build a Spring Boot MVC application with database integration.

Prerequisites

Before we begin, ensure you have the following installed:

  • Java Development Kit (JDK)

  • Integrated Development Environment (IDE) like IntelliJ IDEA or Eclipse

  • Apache Maven (for managing dependencies)

Step 1: Create a Spring Boot Project

  1. Visit the Spring Initializr website (https://start.spring.io/).

  2. Configure your project as follows:

    • Project: Maven Project

    • Language: Java

    • Spring Boot: Choose the latest stable version.

    • Project Metadata: Fill in your project's Group, Artifact, and Package information.

    • Dependencies: Select "Spring Web" and "Spring Data JPA."

  3. Click "Generate" to download the project as a ZIP file.

  4. Extract the downloaded ZIP file to your preferred location.

Step 2: Define the Entity

Create a simple entity class to represent items in your application. For this example, let's create an Item class:

import javax.persistence.*;

@Entity
public class Item {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String description;

    // Constructors, getters, setters
}

This class uses JPA annotations to map it to a database table. It includes an ID, name, and description fields.

Step 3: Create a Repository

Create a repository interface to handle database operations for the Item entity. Create a new Java class called ItemRepository:

import org.springframework.data.jpa.repository.JpaRepository;

public interface ItemRepository extends JpaRepository<Item, Long> {
    // You can define custom query methods here if needed
}

Spring Data JPA provides methods like save, findAll, findById, and more, which you can use without implementing them manually.

Step 4: Create a Controller

Create a controller to handle web requests related to items. Create a new Java class called ItemController:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/items")
public class ItemController {
    private final ItemRepository itemRepository;

    @Autowired
    public ItemController(ItemRepository itemRepository) {
        this.itemRepository = itemRepository;
    }

    @GetMapping("/list")
    public String listItems(Model model) {
        List<Item> items = itemRepository.findAll();
        model.addAttribute("items", items);
        return "item-list";
    }

    @GetMapping("/add")
    public String addItemForm(Model model) {
        model.addAttribute("item", new Item());
        return "item-form";
    }

    @PostMapping("/add")
    public String addItem(@ModelAttribute Item item) {
        itemRepository.save(item);
        return "redirect:/items/list";
    }
}

This controller defines three methods: listItems to list items, addItemForm to display a form for adding items, and addItem to handle the form submission and save items to the database.

Step 5: Create HTML Templates

Create HTML templates for listing items and adding items. Inside the src/main/resources/templates folder, create two HTML files named item-list.html and item-form.html. These templates define the UI for listing and adding items.

item-list.html:

<!DOCTYPE html>
<html xmlns:th="<http://www.thymeleaf.org">>
<head>
    <meta charset="UTF-8">
    <title>Item List</title>
</head>
<body>
    <h1>Item List</h1>
    <ul>
        <li th:each="item : ${items}" th:text="${item.name}"></li>
    </ul>
    <a href="/items/add">Add Item</a>
</body>
</html>

item-form.html:

<!DOCTYPE html>
<html xmlns:th="<http://www.thymeleaf.org">>
<head>
    <meta charset="UTF-8">
    <title>Add Item</title>
</head>
<body>
    <h1>Add Item</h1>
    <form th:action="@{/items/add}" th:object="${item}" method="post">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name" th:field="*{name}" required>
        <br>
        <label for="description">Description:</label>
        <input type="text" id="description" name="description" th:field="*{description}">
        <br>
        <button type="submit">Save</button>
    </form>
    <a href="/items/list">Back to List</a>
</body>
</html>

These templates use Thymeleaf, a popular templating engine for Spring Boot applications.

Step 6: Configure the Database

In your application.properties file (located in src/main/resources), add the following database configuration for the H2 in-memory database:

# H2 Database Configuration
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.hibernate.ddl-auto=update

This configuration tells Spring Boot to use an H2 in-memory database and automatically generate tables based on your entity classes.

Step 7: Run the Application

You can run your Spring Boot application using your IDE or by using Maven. If you're using Maven, open a terminal in your project directory and run the following command:

mvn spring-boot:run

Once the application starts, you can access it by opening a web browser and navigating to <http://localhost:8080/items/list> (or the port you specified in application.properties). You should see the item list page, where you can add and view items.

Conclusion

In this blog, you've learned how to build a Spring Boot MVC application with database integration. You created an entity, repository, controller, and HTML templates, and configured an H2 in-memory database. This example provides a foundation for building more complex web applications with Spring Boot, allowing you to add features like editing, deleting, and more. Spring Boot's simplicity and productivity make it an excellent choice for developing modern web applications. Happy coding!

Comments

Popular posts from this blog

VoIP with Asterisk Server

Building a Spring Boot MVC Application with MariaDB and Native JDBC

Exploring the New Features of Spring Framework 6.0.12 with Examples