Skip to content

Commit 8f50b36

Browse files
committed
BAEL-7610 Code for the improvement Ignore Null Fields with Spring BeanUtils copyProperties
1 parent 3317284 commit 8f50b36

File tree

3 files changed

+43
-0
lines changed

3 files changed

+43
-0
lines changed

libraries-apache-commons/src/main/java/com/baeldung/commons/beanutils/CourseEntity.java

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,4 +32,9 @@ public void setStudent(String id, Student student) {
3232
public Student getStudent(String enrolledId) {
3333
return students.get(enrolledId);
3434
}
35+
36+
public Map<String, Student> getStudents() {
37+
return students;
38+
}
39+
3540
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package com.baeldung.commons.beanutils;
2+
3+
import java.lang.reflect.InvocationTargetException;
4+
5+
import org.apache.commons.beanutils.BeanUtilsBean;
6+
7+
public class IgnoreNullBeanUtilsBean extends BeanUtilsBean {
8+
9+
@Override
10+
public void copyProperty(Object dest, String name, Object value) throws IllegalAccessException, InvocationTargetException {
11+
if (value != null) {
12+
super.copyProperty(dest, name, value);
13+
}
14+
}
15+
16+
}

libraries-apache-commons/src/test/java/com/baeldung/commons/beanutils/CourseServiceUnitTest.java

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
package com.baeldung.commons.beanutils;
22

3+
import static org.assertj.core.api.Assertions.assertThat;
4+
import static org.junit.jupiter.api.Assertions.assertEquals;
5+
36
import java.lang.reflect.InvocationTargetException;
47
import java.util.Arrays;
58
import java.util.List;
@@ -50,4 +53,23 @@ public void givenCopyProperties_whenCopyCourseToCourseEntity_thenCopyPropertyWit
5053
Assert.assertEquals(course.getCodes(), courseEntity.getCodes());
5154
Assert.assertNull(courseEntity.getStudent("ST-1"));
5255
}
56+
57+
@Test
58+
public void givenNullName_whenCopyProperties_thenCopyEveryPropertyButName() throws IllegalAccessException, InvocationTargetException {
59+
Course originalCourse = new Course();
60+
originalCourse.setName(null);
61+
originalCourse.setCodes(Arrays.asList("CS"));
62+
originalCourse.setEnrolledStudent("ST-1", new Student());
63+
64+
CourseEntity destCourse = new CourseEntity();
65+
destCourse.setName("entityName");
66+
67+
IgnoreNullBeanUtilsBean ignoreNullBeanUtilsBean = new IgnoreNullBeanUtilsBean();
68+
ignoreNullBeanUtilsBean.copyProperties(destCourse, originalCourse);
69+
70+
assertEquals("entityName", destCourse.getName());
71+
assertThat(destCourse.getCodes()).containsExactly("CS");
72+
assertThat(destCourse.getStudents()).isEmpty();
73+
}
74+
5375
}

0 commit comments

Comments
 (0)