VOOZH about

URL: https://www.geeksforgeeks.org/advance-java/spring-data-jpa-insert-data-in-mysql-table/

⇱ Spring Data JPA - Insert Data in MySQL Table - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Spring Data JPA - Insert Data in MySQL Table

Last Updated : 12 Nov, 2025

Spring Data JPA simplifies database operations in Spring Boot by eliminating boilerplate code. It provides built-in methods to perform CRUD (Create, Read, Update, Delete) operations on relational databases like MySQL.

In this article, we will learn how to insert data into a MySQL database using Spring Boot, Spring Data JPA, and Hibernate with the save() method of JpaRepository.

JPARepository.save() Method

The save() method in JpaRepository is used to insert or update an entity in the database.

userRepository.save(user);

If the entity does not exist, it will be inserted. If it exists (based on its primary key), it will be updated.

Step By Step Implementation

Step 1: Create a Spring Boot Project

1. Visit Spring Initializr.

2. Select:

  • Spring Boot Version: 3.x
  • Project: Maven Project
  • Language: Java

3. Add the following dependencies:

  • Spring Web
  • Spring Data JPA
  • MySQL Driver

Click Generate, extract the project, and open it in your IDE.

Note: Use JDK 17 or later.

👁 Spring-Initializr
Spring Initializr

Step 2: Configure pom.xml

Ensure your pom.xml contains the required dependencies and uses a supported Java version.

Step 3: Configure Database in application.properties

Set up your database credentials and Hibernate configuration in src/main/resources/application.properties:

spring.datasource.url=jdbc:mysql://localhost:3306/user_db
spring.datasource.username=${DB_USERNAME}
spring.datasource.password=${DB_PASSWORD}

spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

Note: Replace user_db with your database name and ensure MySQL is running locally.

Step 4: Create Entity Class

Define an entity class to map Java objects to the database table.

User.java:

  •  @Entity marks this class as a JPA entity.
  • @Table(name = "users") specifies the database table name.
  • @GeneratedValue automatically generates the primary key value.

Step 5: Create Repository Interface

The repository interface extends JpaRepository to enable CRUD operations.

UserRepository.java:

 No implementation is required since Spring Data JPA automatically provides one at runtime.

Step 6: Insert Data Using save() Method

Use the CommandLineRunner interface to execute code after the application starts.

Step 7: Run the Application

Run the application from your IDE or using the command:

mvn spring-boot:run

The Spring Boot application will start and automatically insert a new record into the users table.

Output:

👁 Image

Step 8: Verify the Data in MySQL 

Execute the following SQL query in MySQL to confirm insertion:

SELECT * FROM users;

Output:

👁 Image
Comment

Explore