Bulk data to find exists or not : Spring Data JPA

Viewed 1077

I get an Post request that would give me a List<PersonApi> Objects

class PersonApi {
  private String name;
  private String age;
  private String pincode ;
}

And I have an Entity Object named Person

@Entity
@Table(name = "person_master")
public class Person{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    Long id;

    @Column(name = "name")
    String name;

    @Column(name = "age")
    String age;

    @Column(name = "pincode ")
    String pincode ;
}

My record from Post request would look something like this (pseudocode representation of the data below)

[
"Arun","33","09876gh"
"James","34","8765468"
]

I need to do a bulk-validation using Spring JPA.. Give the List<PersonApi> and get a True or False based on the condition that all the entries in the PersonApi objects list should be there in the database.

How to do this ?

2 Answers

The selected answer is not a right one. (not always right) You are selecting the whole database to check for existence. Unless your use case is very special, i.e. table is very small, this will kill the performance.

The proper way may start from issuing repository.existsById(id) for each Person, if you never delete the persons, you can even apply some caching on top of it.

exists

Pseudo Code:

List<PersonApi> personsApiList = ...; //from request
List<Person> result = personRepository.findAll();

in your service class you can access your repository to fetch all database entities and check if your list of personapi's is completeley available.

boolean allEntriesExist = result.stream().allMatch(person -> personsApiList.contains(createPersonApiFromPerson(person)));

public PersonApi createPersonApiFromPerson(Person person){
   return new PersonApi(person.getName(), person.getAge(), person.getPincode());
}
Related