Commit 6481b2b4 authored by Alex Segers's avatar Alex Segers

Merge branch 'fix/student_service#updateStudent' into 'master'

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

See merge request !3
parents acfd1df3 78e7b802
...@@ -3,6 +3,7 @@ package com.student.details.models; ...@@ -3,6 +3,7 @@ package com.student.details.models;
import lombok.Data; import lombok.Data;
import javax.persistence.*; import javax.persistence.*;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
import java.lang.reflect.Field;
import java.time.LocalDate; import java.time.LocalDate;
@Entity @Entity
...@@ -21,4 +22,18 @@ public class Student { ...@@ -21,4 +22,18 @@ public class Student {
@NotNull @NotNull
private LocalDate dateOfBirth; 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) { }
}
} }
...@@ -42,12 +42,8 @@ public class StudentService { ...@@ -42,12 +42,8 @@ public class StudentService {
public Student updateStudent(Long studentId, Student studentDetails) throws ResourceNotFoundException { public Student updateStudent(Long studentId, Student studentDetails) throws ResourceNotFoundException {
Student student = studentRepository.findById(studentId) Student student = studentRepository.findById(studentId)
.orElseThrow(() -> new ResourceNotFoundException("Student id: " + studentId + " not found")); .orElseThrow(() -> new ResourceNotFoundException("Student id: " + studentId + " not found"));
student.copyFields(studentDetails);
student.setFirstName(studentDetails.getFirstName()); return studentRepository.save(student);
student.setLastName(studentDetails.getLastName());
Student updatedStudent = studentRepository.save(student);
return updatedStudent;
} }
......
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