Commit 78e7b802 authored by Alex Segers's avatar Alex Segers

Fix UserService#updateStudent to copy all non-null fields from request body

parent cbf770ae
......@@ -3,6 +3,7 @@ package com.student.details.models;
import lombok.Data;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.lang.reflect.Field;
import java.time.LocalDate;
@Entity
......@@ -21,4 +22,18 @@ public class Student {
@NotNull
private LocalDate dateOfBirth;
public void copyFields(Student sourceStudent) {
try {
for (Field field : sourceStudent.getClass().getDeclaredFields()) {
String fieldName = field.getName();
Object sourceValue = field.get(sourceStudent);
if (!fieldName.equals("id") && null != sourceValue) {
Field destField = this.getClass().getDeclaredField(fieldName);
destField.set(this, sourceValue);
}
}
} catch (Exception ignore) { }
}
}
......@@ -44,12 +44,8 @@ public class StudentService {
public Student updateStudent(Long studentId, Student studentDetails) throws ResourceNotFoundException {
Student student = studentRepository.findById(studentId)
.orElseThrow(() -> new ResourceNotFoundException("Student id: " + studentId + " not found"));
student.setFirstName(studentDetails.getFirstName());
student.setLastName(studentDetails.getLastName());
Student updatedStudent = studentRepository.save(student);
return updatedStudent;
student.copyFields(studentDetails);
return studentRepository.save(student);
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment