![]() |
VOOZH | about |
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.
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.
1. Visit Spring Initializr.
2. Select:
3. Add the following dependencies:
Click Generate, extract the project, and open it in your IDE.
Note: Use JDK 17 or later.
Ensure your pom.xml contains the required dependencies and uses a supported Java version.
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.
Define an entity class to map Java objects to the database table.
User.java:
The repository interface extends JpaRepository to enable CRUD operations.
UserRepository.java:
No implementation is required since Spring Data JPA automatically provides one at runtime.
Use the CommandLineRunner interface to execute code after the application starts.
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:
👁 ImageExecute the following SQL query in MySQL to confirm insertion:
SELECT * FROM users;
Output:
👁 Image