I am writing a Java code in Spring JPA which can add or update a data when saveData function is called. what I am trying to do is that if data is new it gets added as a new record in the database or else it will be updated.
public void saveData(List<StudentTable> studentTableList){
List< StudentTable > data= new ArrayList<>();
for(StudentTable dt: studentTableList){
if(dt.getStudentId() ==null) {
data.add(dt);
}else{
studentRepository.findById(dt.getStudentId()).map(
student->{
student.setFirstName(dt.getFirstName());
student.setLastName(dt.getLastName ());
student.setPhone(dt.getPhone());
student.setAddress(dt.getAddress());
return data.add(student);
});
}
studentRepository.saveAll(data);
data.clear();
}
}
While this code is working fine I see performance issues as my entries grow. I see that update and select queries are run for each row of the table which is slowing down the performance.
I want to know if there is any way to run queries only for those rows which are updated or added on a single post request or to improve the performance?