Inserting Data into Your MySQL Database with Spring Boot

Harindra Dilshan
5 min readSep 16, 2024

--

Now that we have successfully established a connection between our Spring Boot backend and the MySQL database, our next step is to populate the database with relevant data. To streamline this process, we will incorporate the Lombok dependency into our project. This dependency can be conveniently added to the <dependencies> section of our pom.xml file.

    <dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>

Create packages structure.

Spring boot main project structure

Create the following packages in your project as shown in the image above: controller, dto, entity, repository, and service.

Create user entity

Let’s create user entity in entity package.

Create User class in entity package.

package com.example.demo.entity;

import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@NoArgsConstructor
@AllArgsConstructor
@Data
@Entity
public class User {
@Id
private long id;
private String name;
private String address;
}

We need to add the @Entity annotation to indicate that the class represents an entity. However, an error occurs because we need to specify the primary key for the entity. To resolve this, use the @Id annotation to indicate the primary key field.

@NoArgsConstructor  // constructor with no argument
@AllArgsConstructor // constructor with all argument
@Data // getters and setters

By incorporating the Lombok dependency, we can significantly streamline our development process. Lombok provides annotations that automatically generate boilerplate code, such as constructors (including all-args and no-args) and getters and setters. This eliminates the need for manual creation of these elements, resulting in cleaner, more concise, and maintainable code.

Create user dto

Create a new class named UserDTO within the dto package to represent user data for transfer between layers of your application.

package com.example.demo.dto;  

import jakarta.persistence.Id;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@NoArgsConstructor
@AllArgsConstructor
@Data
public class UserDTO {
private int id;
private String name;
private String address;
}

Create user repository

Create a new interface named UserRepository within the repository package and extend the JpaRepository<User, Long> interface to provide CRUD operations for user entities, where User represents the entity class and Long represents the primary key type.

package com.example.demo.repository;

import com.example.demo.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepo extends JpaRepository<User, Long> {
}

Create user service

Create a new class named UserService within the service package to provide business logic for user-related operations, such as creating, retrieving, updating, and deleting users.

package com.example.demo.service;  
import com.example.demo.dto.UserDTO;
import com.example.demo.entity.User;
import com.example.demo.reposity.UserRepo;
import jakarta.transaction.Transactional;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
@Transactional
public class UserService {
@Autowired
private UserRepo userRepo;
@Autowired
private ModelMapper modelMapper;
public UserDTO saveUser(UserDTO userDTO){
userRepo.save(modelMapper.map(userDTO, User.class));
return userDTO;
}
}

Annotate the UserService class with @Service to indicate its role as a service component within the Spring application context. Additionally, annotate the saveUser method with @Transactional to ensure that the user data is saved in a transactional manner, guaranteeing data consistency in case of errors.

In UserController (not create yet) has a method,

@PostMapping("/saveUser")  
public String saveUser(){
return "seve user";
}

In our application architecture, user data flows through the following sequence: UserController ==> UserService ==> UserRepo. To save data into the database, the UserService interacts with the UserRepo, which handles the data persistence logic. Therefore, to facilitate this process, we need to inject the UserRepo into the UserService. This allows the UserService to delegate the task of data storage to the UserRepo.

Data is passed from the UserController to the UserService through the UserDTO class, which is part of the DTO package. To ensure we correctly handle this data, we need to add a parameter of type UserDTO in the UserService method. This allows the service to receive the data in a structured format before converting it to the corresponding entity and passing it to the save() method for database storage.

There is still an issue because we need to map the data coming from UserDTO to the User entity. Since the controller data must be assigned as an object, we require an additional dependency to handle this conversion. A mapping utility or service can be used to transform the UserDTO into the User entity before passing it to the save() method in the UserService, ensuring the correct format for database storage.

<!-- https://mvnrepository.com/artifact/org.modelmapper/modelmapper -->
<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>2.4.4</version>
</dependency>

After that, we need to inject it as a bean.

package com.example.demo;  
import org.modelmapper.ModelMapper;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Bean
public ModelMapper modelMapper(){
return new ModelMapper();
}
}

Create user controller

In the controller package, create a UserController class.

package com.example.demo.controller;

import com.example.demo.dto.UserDTO;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping(value = "api/v1/user")
@CrossOrigin
public class UserController {
@Autowired
UserService userService;

@PostMapping("/saveUser")
public UserDTO saveUser(@RequestBody UserDTO userDTO){
return userService.saveUser(userDTO);
}
}

The @ResponseBody annotation informs the controller that the returned object is automatically serialized into JSON and sent back as part of the HttpResponse.

Now we can pass data using Postman as a JSON object using postman.

post man example post request

You can now check the previously created database (`userdatabase`) to view the data in the table. The data is successfully stored and correctly displayed, reflecting the changes made through the application.

MySQL example database showing and show table data

--

--