티스토리 뷰

개발을 진행 하는중에 JPA 를 사용하게 되었다.

JPA를 처음 사용해보는 상태에서 CUD 는 JPA 를 이용하고 

SELECT의 경우 MyBatis 를 사용하도록 프로젝트가 구성 되었다.

 

샘플 페이지를 만들어 보니 Update에서 문제가 발생 하였다.

requestDto에서 보내온 정보를 Entity에 넣으면서 데이터가 null 인 부분도 모두 업데이트를 치는 형태로 만들게 되었다.

이 부분을 어떻게 해결할수 있는 부분이 없어서 검색을 하다 보니 너무 편하게 사용할수 있는 소스를 찾았다.

 

@RequestMapping(value = "/rest/user", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public ResponseEntity<?> updateUser(@RequestBody User user) {

   User existing = userRepository.read(user.getId());
   copyNonNullProperties(user, existing);
   userRepository.save(existing);

   // ...
}

public static void copyNonNullProperties(Object src, Object target) {
    BeanUtils.copyProperties(src, target, getNullPropertyNames(src));
}

public static String[] getNullPropertyNames (Object source) {
    final BeanWrapper src = new BeanWrapperImpl(source);
    java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

    Set<String> emptyNames = new HashSet<String>();
    for(java.beans.PropertyDescriptor pd : pds) {
        Object srcValue = src.getPropertyValue(pd.getName());
        if (srcValue == null) emptyNames.add(pd.getName());
    }
    String[] result = new String[emptyNames.size()];
    return emptyNames.toArray(result);
}

 

출처 :: stackoverflow.com/questions/27818334/jpa-update-only-specific-fields

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함