Skip to content

Commit

Permalink
Merge pull request eugenp#16663 from thibaultfaure/improvements/BAEL-…
Browse files Browse the repository at this point in the history
…7610-ignore-null-fields-with-beanutils

BAEL-7610 Code for the improvement Ignore Null Fields with Spring Bea…
  • Loading branch information
vinipx authored May 17, 2024
2 parents aad4d09 + 8f50b36 commit b8ff33e
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,9 @@ public void setStudent(String id, Student student) {
public Student getStudent(String enrolledId) {
return students.get(enrolledId);
}

public Map<String, Student> getStudents() {
return students;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package com.baeldung.commons.beanutils;

import java.lang.reflect.InvocationTargetException;

import org.apache.commons.beanutils.BeanUtilsBean;

public class IgnoreNullBeanUtilsBean extends BeanUtilsBean {

@Override
public void copyProperty(Object dest, String name, Object value) throws IllegalAccessException, InvocationTargetException {
if (value != null) {
super.copyProperty(dest, name, value);
}
}

}
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
package com.baeldung.commons.beanutils;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;

import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.List;
Expand Down Expand Up @@ -50,4 +53,23 @@ public void givenCopyProperties_whenCopyCourseToCourseEntity_thenCopyPropertyWit
Assert.assertEquals(course.getCodes(), courseEntity.getCodes());
Assert.assertNull(courseEntity.getStudent("ST-1"));
}

@Test
public void givenNullName_whenCopyProperties_thenCopyEveryPropertyButName() throws IllegalAccessException, InvocationTargetException {
Course originalCourse = new Course();
originalCourse.setName(null);
originalCourse.setCodes(Arrays.asList("CS"));
originalCourse.setEnrolledStudent("ST-1", new Student());

CourseEntity destCourse = new CourseEntity();
destCourse.setName("entityName");

IgnoreNullBeanUtilsBean ignoreNullBeanUtilsBean = new IgnoreNullBeanUtilsBean();
ignoreNullBeanUtilsBean.copyProperties(destCourse, originalCourse);

assertEquals("entityName", destCourse.getName());
assertThat(destCourse.getCodes()).containsExactly("CS");
assertThat(destCourse.getStudents()).isEmpty();
}

}

0 comments on commit b8ff33e

Please sign in to comment.