0

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?

Kumar_Maddy
  • 89
  • 2
  • 10

2 Answers2

0

What about 2 blocks of code for each case?

Student student = studentRepository.findById(dt.getStudentId());
if(student == null){
  Student newStudent = new Student();
  //add data
  newStudent.save();
} else {
  student.setFirstName(dt.getFirstName());
  student.setLastName(dt.getLastName ());
  student.setPhone(dt.getPhone());
  student.setAddress(dt.getAddress());
  student.update();
}
0

You can follow what @fladdimir mentioned. Or, here is my suggestion[will not provide any code, leaving up to you]:

  1. filter objects which are old ones[contains id as I can see from your code] and news ones in two separate lists
  2. List all ids
  3. use id <--> object as keyValue in a map
  4. Query all the objects with idList you got using IN clause
  5. Now, set value as you are doing in your 2nd code block from the map, add them in a list
  6. merge this list with new objectList
  7. save them altogether with saveAll(your_merged_list)

I am not saying this is the optimized way, but at least you can reduce load on your db.

user404
  • 1,934
  • 1
  • 16
  • 32