DEV Community

Cover image for How To Update Or Insert A Record In Spring Data JPA
Maddy
Maddy

Posted on • Updated on • Originally published at techwithmaddy.com

How To Update Or Insert A Record In Spring Data JPA

Do you want to know how to update an existing record or insert a new one using Spring Boot?

This article is for you.

Let's imagine the following scenarios:

  1. We have an existing customer who wants to amend his phone number because it was wrong.

  2. We have an entirely new customer who wants to register his details.

In one of my previous articles on How To Create A Spring Boot REST API, we have the following method:

    public Customer saveCustomer(Customer savedCustomer) {
        Customer customer = new Customer();
        customer.setFirstName(savedCustomer.getFirstName());
        customer.setLastName(savedCustomer.getLastName());
        customer.setEmail(savedCustomer.getEmail());
        customer.setPhoneNumber(savedCustomer.getPhoneNumber());
        return customerRepository.save(savedCustomer);
    }
Enter fullscreen mode Exit fullscreen mode

The method above only covers scenario number 2.

We can refactor this method to perform an upsert operation.

#2 WHAT IS AN UPSERT OPERATION?

An upsert operation is a database operation where we update an existing row if the value is already present in the database. Otherwise, we save the new value into a new row.

#3. HOW DO YOU DO AN UPSERT?

To do this, we have to:

  1. Delete any duplicate entry from the Customer table to avoid the 1062 - Duplicate Entry error.

  2. We'll use the email to uniquely identify a customer. Therefore, make the email column unique.

ALTER TABLE customer ADD UNIQUE (email);
Enter fullscreen mode Exit fullscreen mode
  1. Refactor save() method logic so that it checks if an entry exists in the database. If it does, update the existing entry. Otherwise, create a new one and insert it into the database.
    public Customer saveCustomer(Customer savedCustomer) {
        Customer customer =    customerRepository
                .findCustomerByEmail(savedCustomer.getEmail());

        if(customer != null) {
            customer.setFirstName(savedCustomer.getFirstName());
            customer.setLastName(savedCustomer.getLastName());
            customer.setPhoneNumber(savedCustomer.getPhoneNumber());
        } else {
customer = new Customer();
            customer.setFirstName(savedCustomer.getFirstName());
            customer.setLastName(savedCustomer.getLastName());
            customer.setEmail(savedCustomer.getEmail());
            customer.setPhoneNumber(savedCustomer.getPhoneNumber());
        }
        return customerRepository.save(customer);
    }

    public Optional<Customer> getCustomerByEmail(String email){
        Customer customer = customerRepository.findCustomerByEmail(email);

        return Optional.ofNullable(customer);
    }

Enter fullscreen mode Exit fullscreen mode

#3. TESTING ON POSTMAN

Let's test this logic via Postman:

helena-post-request

The record gets updated in the database too.

helena-costa-saved

Now let's try to update Helena's phone number with a different one.

helena-phone-number-updated

In the database, Helena's phone number should be updated (no new row should be created).

helena-phone-number-saved-db

CONCLUSION

I hope you've found this article helpful.

Leave any questions/doubts in the comments below.

Until next time!

FURTHER READING:

Top comments (6)

Collapse
 
rx40 profile image
Petrus-Nauyoma

Hey Maddy. Do you also do UI development?

Collapse
 
maddy profile image
Maddy

I don't, darling.

Collapse
 
rx40 profile image
Petrus-Nauyoma

Cool cool, so are you basically a java backend developer? Or what other roles are you into, your article was very informative.

Thread Thread
 
maddy profile image
Maddy

I work with Java, so I share what I learn on my blog. I'm developing other skills, such as SEO.

Collapse
 
isaacpro01 profile image
ssemugenyi isaac

I do frontend

Collapse
 
junho85 profile image
JunHo Kim (김준호) • Edited
if(customer != null) {
            customer.setFirstName(savedCustomer.getFirstName());
            customer.setLastName(savedCustomer.getLastName());
            customer.setPhoneNumber(savedCustomer.getPhoneNumber());
        } else {
            customer.setFirstName(savedCustomer.getFirstName());
            customer.setLastName(savedCustomer.getLastName());
            customer.setEmail(savedCustomer.getEmail());
            customer.setPhoneNumber(savedCustomer.getPhoneNumber());
        }
Enter fullscreen mode Exit fullscreen mode

I guess it makes NPE when customer is null, doesn't it?