Building a Spring Boot MVC Application with MariaDB and Native JDBC

In this blog post, we will guide you through the process of building a Spring Boot MVC application that integrates with the MariaDB database using native JDBC for data access. We will cover essential steps, including configuring the database connection, defining entities, creating repositories, building controllers, and setting up Thymeleaf templates. By the end of this blog, you'll have a fully functional Spring Boot MVC application for managing products in a MariaDB database.

Prerequisites

Before we start, make sure you have the following prerequisites in place:

  • Java Development Kit (JDK) installed on your machine.

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

  • Apache Maven for managing project dependencies.

  • A running MariaDB database instance.

Step 1: Create a Spring Boot Project

  1. Spring Initializr: Visit the Spring Initializr website (https://start.spring.io/) to create a new Spring Boot project. Configure the project settings 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 "Thymeleaf."

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

  3. Extract the downloaded ZIP file to your preferred location on your local machine.

Step 2: Configure MariaDB Connection

Open the src/main/resources/application.properties file and configure your MariaDB connection details. Replace yourdb, yourusername, and yourpassword with your MariaDB database name, username, and password.

# MariaDB Database Configuration
spring.datasource.url=jdbc:mariadb://localhost:3306/yourdb
spring.datasource.username=yourusername
spring.datasource.password=yourpassword
spring.datasource.driver-class-name=org.mariadb.jdbc.Driver

This configuration tells Spring Boot to connect to your MariaDB database using the native MariaDB JDBC driver.

Step 3: Define the Entity

Create a Product entity class in the src/main/java/com/example/demo directory:

import java.math.BigDecimal;

public class Product {
    private Long id;
    private String name;
    private BigDecimal price;

    // Constructors, getters, and setters
}

The Product class represents the products you'll manage in the database.

Step 4: Create a Repository

Create a repository class that handles database operations using native JDBC:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class ProductRepository {

    private final JdbcTemplate jdbcTemplate;

    @Autowired
    public ProductRepository(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public List<Product> findAll() {
        String sql = "SELECT * FROM products";
        return jdbcTemplate.query(sql, this::mapRowToProduct);
    }

    public Product findById(Long id) {
        String sql = "SELECT * FROM products WHERE id = ?";
        return jdbcTemplate.queryForObject(sql, this::mapRowToProduct, id);
    }

    public void save(Product product) {
        String sql = "INSERT INTO products (name, price) VALUES (?, ?)";
        jdbcTemplate.update(sql, product.getName(), product.getPrice());
    }

    public void update(Product product) {
        String sql = "UPDATE products SET name = ?, price = ? WHERE id = ?";
        jdbcTemplate.update(sql, product.getName(), product.getPrice(), product.getId());
    }

    public void delete(Long id) {
        String sql = "DELETE FROM products WHERE id = ?";
        jdbcTemplate.update(sql, id);
    }

    private Product mapRowToProduct(ResultSet rs, int rowNum) throws SQLException {
        Product product = new Product();
        product.setId(rs.getLong("id"));
        product.setName(rs.getString("name"));
        product.setPrice(rs.getBigDecimal("price"));
        return product;
    }
}

The ProductRepository class defines methods for performing CRUD operations on products using native JDBC.

Step 5: Create a Controller

Create a controller class for handling web requests:

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("/products")
public class ProductController {

    private final ProductRepository productRepository;

    @Autowired
    public ProductController(ProductRepository productRepository) {
        this.productRepository = productRepository;
    }

    @GetMapping("/list")
    public String listProducts(Model model) {
        List<Product> products = productRepository.findAll();
        model.addAttribute("products", products);
        return "product-list";
    }

    @GetMapping("/add")
    public String addProductForm(Model model) {
        model.addAttribute("product", new Product());
        return "product-form";
    }

    @PostMapping("/add")
    public String addProduct(@ModelAttribute Product product) {
        productRepository.save(product);
        return "redirect:/products/list";
    }

    @GetMapping("/edit/{id}")
    public String editProductForm(@PathVariable Long id, Model model) {
        Product product = productRepository.findById(id);
        model.addAttribute("product", product);
        return "product-form";
    }

    @PostMapping("/edit/{id}")
    public String editProduct(@PathVariable Long id, @ModelAttribute Product product) {
        product.setId(id);
        productRepository.update(product);
        return "redirect:/products/list";
    }

    @GetMapping("/delete/{id}")
    public String deleteProduct(@PathVariable Long id) {
        productRepository.delete(id);
        return "redirect:/products/list";
    }
}

The ProductController class defines methods for listing products, displaying a form for adding/editing products, and handling CRUD operations.

Step 6: Create HTML Templates

Create Thymeleaf templates for listing products and adding/editing products:

src/main/resources/templates/product-list.html:

<!DOCTYPE html>
<html xmlns:th="<http://www.thymeleaf.org">>
<head>
    <meta charset="UTF-8">
    <title>Product List</title>
</head>
<body>
    <h1>Product List</h1>
    <table>
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Price</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
            <tr th:each="product : ${products}">
                <td th:text="${product.id}"></td>
                <td th:text="${product.name}"></td>
                <td th:text="${product.price}"></td>
                <td>
                    <a th:href="@{/products/edit/{id}(id=${product.id})}">Edit</a>
                    <a th:href="@{/products/delete/{id}(id=${product.id})}">Delete</a>
                </td>
            </tr>
        </tbody>
    </table>
    <a href="/products/add">Add Product</a>
</body>
</html>

src/main/resources/templates/product-form.html:

<!DOCTYPE html>
<html xmlns:th

="<http://www.thymeleaf.org">>
<head>
    <meta charset="UTF-8">
    <title>Add/Edit Product</title>
</head>
<body>
    <h1>Add/Edit Product</h1>
    <form th:action="@{/products/add}" th:object="${product}" method="post">
        <input type="hidden" th:field="*{id}">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name" th:field="*{name}" required>
        <br>
        <label for="price">Price:</label>
        <input type="text" id="price" name="price" th:field="*{price}" required>
        <br>
        <button type="submit">Save</button>
    </form>
    <a href="/products/list">Back to List</a>
</body>
</html>

These templates use Thymeleaf to display product data and handle form submissions.

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, open a web browser and navigate to <http://localhost:8080/products/list> (or the port you specified in application.properties). You'll see the product list page, where you can add, edit, and delete products.

Congratulations! You've successfully built a Spring Boot MVC application integrated with MariaDB using native JDBC for data access. This example provides a solid foundation for building more complex web applications, and you can extend it by adding additional features, such as validation, security, and more. Spring Boot's simplicity and productivity make it a fantastic choice for developing modern web applications. Happy coding!

Comments

Popular posts from this blog

VoIP with Asterisk Server

Exploring the New Features of Spring Framework 6.0.12 with Examples