0

I have a POST API to create an entity called Person, and I check if person with the name and address exist or not, if not i create a person entity:

class Person {
    UUID id
    String name;
    String address
}

public void createPerson(String name, String addr){
    Person p = repository.findPersonByNameAndAddress(name, addr);
    if (p != null) {
        repository.create(name, addr);
    }
}

If a client calls the POST with same data at the same time I will end up creating two person with same name and address (but different ID). How can i prevent this from happening? I am using spring boot + JPA/Hibernate + postgres

Thanks!

2 Answers 2

3

Such constraints can be enforced only at the database layer. They cannot be handled at the application layer. If, as per your data model, two people cannot have the same name and address, you can add a unique constraint on (name, address) in your database.

ALTER TABLE person
  add CONSTRAINT person_name_address UNIQUE (name, address);

With such a constraint, one of the two API calls will result in a SQLIntegrityConstraintViolationException which you can handle accordingly.

Sign up to request clarification or add additional context in comments.

Comments

0

You can fix it by either of two ways:

  1. Define a unique key constraint for both name and address
  2. Find person by name and address by ignoring case using existsByNameIgnoreCaseAndAddressIgnoreCase

    class PersonDao {
    
       public void createPerson(String name, String addr) {
            boolean isExists = repository.existsByNameIgnoreCaseAndAddressIgnoreCase(name, addr);
            if (!isExists) {
                PersonEntity person = new PersonEntity();
                person.setName(name);
                person.setAddress(addr);
                repository.save(person);
            }
        }
    }
    

1 Comment

Your second point won't work. If you will test it in concurrency environment (send at least 5 requests in the same time) - they all (or part of them) will reach isExists=false and try to create a new entity.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.