I want to know the best and efficient way to update an entity, which is industry practice. What I know at this moment to update an entity
@Service
public class StudentService {
@Autowired
private StudentRepository repository;
public Student findById(Long id) throws EntityNotFoundException {
return repository.findById(id).orElseThrow(() -> new EntityNotFoundException("Student not found with id: " + id));
}
public Student updateStudent(Long id, Student updatedData) throws EntityNotFoundException {
Student existingStudent = findById(id);
existingStudent.setFirstName(updatedData.getFirstName());
existingStudent.setLastName(updatedData.getLastName());
existingStudent.setEmail(updatedData.getEmail());
existingStudent.setDepartment(updatedData.getDepartment());
existingStudent.setPhone(updatedData.getPhone());
return repository.save(existingStudent);
}
}
Here I had to manually set all the fields. If I had 20+ fields, was it an efficient approach to update an entity? What is the efficient approach to do that?