Create Restapi to save json array list in database using JPA and spring boot

How to create a rest API  to save the JSON array list into the database using JPA and Spring boot.

Here in this tutorial, will store the user’s information in the MySQL database that is coming from the postman in the form of a JSON array and contains the list of users that we need to register.

let’s create RestAPI in spring boot which will take a user list in JSON as input and store the information in a database using JPA.

UserEntity:

Entities define the database table and getter and setter. In the below UserEntity.java, @Entity annotation converts the class to an entity.

@Table(name = "USER") is used to create a “user” table in the database with the attributes id, username, password, email, role, and enabled status.

Also, the user class contains getter and setter methods for all the above user properties.

package com.insuranceapi.entity;

import javax.persistence.*;

@Entity
@Table(name = "USER")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String username;
    private String password;
    private String email;
    private String role;
    private boolean enabled;

    //more properties as your project requirements


    public User() {
    }

    public User(Long id, String username, String password, String email, String role, boolean enabled) {
        this.id = id;
        this.username = username;
        this.password = password;
        this.email = email;
        this.role = role;
        this.enabled = enabled;
    }

    public Long getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getRole() {
        return role;
    }

    public void setRole(String role) {
        this.role = role;
    }

    public boolean isEnabled() {
        return enabled;
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", email='" + email + '\'' +
                ", role='" + role + '\'' +
                ", enabled=" + enabled +
                '}';
    }
}

User Repository

Create an Interface for User Repository with the name “UserRepository .java” that will extend the JpaRepository<Entity_Name, PrimaryKeyType>

public interface UserRepository extends JpaRepository<User, Long> {
    //username , it will return the user of given username
    public User findByUsername(String username);
}

Restapi to save JSON array list

Under the user controller class create a RestAPI with @PostMapping(“/registration”) that will call CreateUser() method from the service and return the user entity.

@PostMapping("/registration")
    public ResponseEntity<?> createUser(@RequestBody List<User> entity) {
        
        System.out.println(entity.toString());

        ResponseEntity<?> userEntity = userService.CreateUser(entity);
        System.out.println("userEntity:" + userEntity);
        
        return userEntity;
    }

Services

Under the service, the class creates a method “CreateUser()” it will take the user list a parameter and save the data into the database using userRepository.saveAll(entity), and return the userlist a response.

public ResponseEntity<?> CreateUser(List<User> entity) {
        User userEntity = null;
        List<User> userlist = new ArrayList<>();
        try {
            userlist = userRepository.saveAll(entity);

        } catch (Exception e) {
            e.printStackTrace();
            throw new RecordNotFoundException("somthing went Wrong");
        }
        return new ResponseEntity<>(userlist, HttpStatus.OK);
    }

RestAPI to save list with validation in Spring boot

Let’s suppose, in the above API call we need to implement the API validation as the username should not be duplicate then will do some modifications in the service class for the CreateUser method.

public ResponseEntity<?> CreateUser(List<User> entity) {
        User userEntity = null;
        List<User> userlist = new ArrayList<>();
        try {
            for (User user2 : entity) {
                System.out.println("user2.getUsername(): "+user2.getUsername());
                User user = userRepository.findByUsername(user2.getUsername());
                if(user == null) {
                    userEntity  = userRepository.save(user2);
                    userlist.add(userEntity);
                }else {
                    System.out.println("Duplicate username");
                    throw new RecordNotFoundException("User name is already available");
                }
            }
            
        }catch (Exception e) {
            
            throw new RecordNotFoundException("User name is already available");
        }
        return new ResponseEntity<>(userlist,HttpStatus.OK);
    }

ReatAPI payload:

[
{
"firstName": "User",
"lastName": "User",
"gender": "Male",
"city": "fgfg",
"address": "gfdg gfgdfgd 5 fgfgfdg",
"username": "hhhjjj",
"password": "user",
"email": "user@gmail.com",
"role":"User"
},
{
"firstName": "User1",
"lastName": "User1",
"gender": "Male",
"city": "fgfg",
"address": "gfdg gfgdfgd 5 fgfgfdg",
"username": "iiiiiiooiiiiiiii",
"password": "user1",
"email": "user@gmail.com",
"role":"User"
}
]

Leave a Comment

Your email address will not be published. Required fields are marked *