Spring Data JPA with MySQL: A Step-by-Step Tutorial

This tutorial will guide you through the process of setting up and using Spring Data JPA with MySQL in a Spring Boot application.

Prerequisites

  • JDK 17 or later
  • MySQL Database
  • Maven or Gradle
  • IDE (IntelliJ IDEA, Eclipse, etc.)

Step 1: Set Up a Spring Boot Project

1.1 Create a New Spring Boot Project

Use Spring Initializr to create a new project with the following dependencies:

  • Spring Web
  • Spring Data JPA
  • MySQL Driver

Download and unzip the project, then open it in your IDE.

1.2 Configure application.properties

Set up the application properties for your project to connect to a MySQL database. This file is located in the src/main/resources directory.

# src/main/resources/application.properties

# MySQL Database configuration
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=root

# JPA configuration
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect

Explanation:

  • Configures the connection to the MySQL database.
  • Enables SQL logging.
  • Sets up JPA to update the database schema automatically.
  • Specifies the Hibernate dialect for MySQL.

Step 2: Define the Entity Class

2.1 Create the Product Entity

Create an entity class to represent a product in the database.

package com.example.demo.entity;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;

@Entity
public class Product {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private double price;

    // Getters and setters
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }
}

Explanation:

  • @Entity: Specifies that the class is an entity and is mapped to a database table.
  • @Id and @GeneratedValue: Indicates the primary key and its generation strategy.

Step 3: Create the Repository Interface

3.1 Create the ProductRepository

Create a repository interface to perform CRUD operations on the Product entity.

package com.example.demo.repository;

import com.example.demo.entity.Product;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
}

Explanation:

  • @Repository: Indicates that the interface is a Spring Data repository.
  • JpaRepository<Product, Long>: Provides CRUD operations for the Product entity.

Step 4: Create Service and Controller Layers

4.1 Create the ProductService

Create a service class to handle business logic related to products.

package com.example.demo.service;

import com.example.demo.entity.Product;
import com.example.demo.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Service
public class ProductService {

    @Autowired
    private ProductRepository productRepository;

    public List<Product> getAllProducts() {
        return productRepository.findAll();
    }

    public Optional<Product> getProductById(Long id) {
        return productRepository.findById(id);
    }

    public Product createProduct(Product product) {
        return productRepository.save(product);
    }

    public void deleteProduct(Long id) {
        productRepository.deleteById(id);
    }
}

Explanation:

  • @Service: Marks the class as a service component in Spring.
  • ProductRepository: Injected to interact with the database.

4.2 Create the ProductController

Create a REST controller to expose endpoints for interacting with products.

package com.example.demo.controller;

import com.example.demo.entity.Product;
import com.example.demo.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

@RestController
@RequestMapping("/products")
public class ProductController {

    @Autowired
    private ProductService productService;

    @GetMapping
    public List<Product> getAllProducts() {
        return productService.getAllProducts();
    }

    @GetMapping("/{id}")
    public Optional<Product> getProductById(@PathVariable Long id) {
        return productService.getProductById(id);
    }

    @PostMapping
    public Product createProduct(@RequestBody Product product) {
        return productService.createProduct(product);
    }

    @DeleteMapping("/{id}")
    public void deleteProduct(@PathVariable Long id) {
        productService.deleteProduct(id);
    }
}

Explanation:

  • @RestController: Marks the class as a REST controller.
  • @RequestMapping("/products"): Maps the controller to /products endpoint.
  • @GetMapping, @PostMapping, @DeleteMapping: Maps HTTP GET, POST, and DELETE requests respectively.
  • @RequestBody: Binds the HTTP request body to the Product parameter.
  • @PathVariable: Binds the URI template variable to the method parameter.

Step 5: Running and Testing the Application

5.1 Run the Application

Run the Spring Boot application using your IDE or the command line:

./mvnw spring-boot:run

5.2 Test the Endpoints

Use a tool like Postman or your browser to test the endpoints.

Create a Product

  • URL: http://localhost:8080/products
  • Method: POST
  • Body:
    {
        "name": "Sample Product",
        "price": 100.0
    }
    

Get All Products

  • URL: http://localhost:8080/products
  • Method: GET

Get a Product by ID

  • URL: http://localhost:8080/products/{id}
  • Method: GET

Delete a Product

  • URL: http://localhost:8080/products/{id}
  • Method: DELETE

Conclusion

In this tutorial, you have learned how to configure and use Spring Data JPA with MySQL in a Spring Boot 3.2 application. We covered:

  • Setting up a Spring Boot project with Spring Data JPA and MySQL.
  • Defining an entity class and repository.
  • Creating service and controller layers.
  • Running and testing the application using REST endpoints.

By following these steps, you can effectively manage and interact with a MySQL database in your Spring Boot applications using Spring Data JPA.


Comments