Springboot

JPA update시에 dto null 체크및 feild 유무 판단하는 util class

25G 2022. 10. 28. 10:33

Jpa를 사용하다 보면 update를 할 때 dto에 @Valid를 활용해서 밸리데이션 체크를 하기도 애매하고 api서버로써 클라이언트와 통신을 하다 보면 리 엑트에서 undifind로 필드조차도 보내지지 않거나 null값이 들어가는 것을 서버에서 체크해줄 필요가 있다. 그런데 문제는 너무 귀찮다는 것입니다. 필드마다 null체크를 해서 setter로 더티 체킹을 유도하는 작업이 update시에 굉장히 귀찮고 피곤했습니다. 그래서 다음과 같은 util class를 만들어 봤습니다.

/**
 * update시에 null과 field가 없는 것을 체크해서 dto에 데이터가 있는부분만 entity 객체에 입혀주는 util class
 */
public class DtoFieldEmptyChecker {

    public static void copyNonNullProperties(Object entity, Object dto) {
        BeanUtils.copyProperties(dto, entity, getNullFieldsName(entity, dto));
    }

    public static String[] getNullFieldsName(Object entity, Object dto) {
        final BeanWrapper entityBean = new BeanWrapperImpl(entity);
        PropertyDescriptor[] entityPds = entityBean.getPropertyDescriptors();

        final BeanWrapper dtoBean = new BeanWrapperImpl(dto);
        PropertyDescriptor[] dtoPds = dtoBean.getPropertyDescriptors();

        Set<String> ignoreKeys = new HashSet<>();
        for (PropertyDescriptor dtoPd : dtoPds) {
            Object beanValue = dtoBean.getPropertyValue(dtoPd.getName());
            if (beanValue == null) ignoreKeys.add(dtoPd.getName());
            if (Arrays.stream(entityPds).filter(field -> dtoPd.getName().equals(field.getName())).count() == 0) ignoreKeys.add(dtoPd.getName());
        }
        String[] result = new String[ignoreKeys.size()];
        return ignoreKeys.toArray(result);
    }
}

위 코드는 쉽게 말해서 판화처럼 필요없는부분(null, empty)인 필드만 ignore 시키고 데이터가 있는 필드만 도장 찍듯이 entity에 찍어주는 util class로 제가 한번 만들어봤습니다.(update 할 때 dto 필드마다 null 체크하는 것이 겁나 귀찮았기 때문이죠...