springboot 에서@DynamicUpdate 주석 이 잘못 되 었 습 니 다.

springboot 에서@DynamicUpdate 주석 이 잘못 되 었 습 니 다 해결 방안
닥 친 문제
프로젝트 에서 jpa 를 사용 하 는 것 은 이전에 사용 해 본 적 이 없 기 때문에 구 덩이 를 밟 는 것 은 불가피 하 다.
사용 하 는 과정 에서 기록 한 필드 를 업데이트 하려 고 합 니 다.업데이트 에 성공 한 후에 전체 기록 은 제 가 업데이트 한 필드 만 남 았 고 다른 것 은 모두 비어 있 습 니 다.
이 업 데 이 트 는 전체 덮어 쓰기 입 니 다.필드 마다 update,실체 류 에 할당 되 지 않 은 필드 에 대해 서도 빈 값 set 을 직접 보 냅 니 다.
해결 방안 을 모색 하 다
这里写图片描述
이렇게 쉽게 해결 할 수 있어 서 다행 인 데,갑자기 이렇게 간단 하지 않다 는 것 을 알 게 되 었 다.
这里写图片描述
군중 의 힘 은 무궁무진 하 다.나 는 즉시 이 주해 가 왜 무효 인지 알 았 는데,원래 그것 의 용 도 를 잘못 알 았 다.
하나의 해결 방안.
방금 수많은 화살표 가 가리 키 는 댓 글 에서 말 한 바 와 같이 findOne 으로 원 가 를 찾 아 낸 다음 에 수정 하고 자 하 는 새로운 필드 값 을 부여 합 니 다.
생각 은 매우 간단 하 다.여 기 는 주로 대상 이 복사 한 코드 를 붙인다.데이터베이스 에서 찾 아 낸 대상 을 target 이 라 고 부 르 고 수정 할 필드 를 포함 하 는 대상 을 source 라 고 부 릅 니 다.물론 마지막 으로 우리 save 는 수 정 된 target 입 니 다.
BeanCopyUtil:

import ch.qos.logback.core.joran.util.beans.BeanUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import java.util.HashSet;
import java.util.Set;
/**
 * created by xxx 2018/7/21
 */
public class BeanCopyUtil {
    //source         target 
    public static <T> void beanCopy(T source, T target) {
        BeanUtils.copyProperties(source, target, getNullPropertyNames(source));
    }
    //source         target ,         ,              (      )
    public static <T> void beanCopyWithIngore(T source, T target, String... ignoreProperties) {
        String[] pns = getNullAndIgnorePropertyNames(source, ignoreProperties);
        BeanUtils.copyProperties(source, target, pns);
    }
    public static String[] getNullAndIgnorePropertyNames(Object source, String... ignoreProperties) {
        Set<String> emptyNames = getNullPropertyNameSet(source);
        for (String s : ignoreProperties) {
            emptyNames.add(s);
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }
    public static String[] getNullPropertyNames(Object source) {
        Set<String> emptyNames = getNullPropertyNameSet(source);
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }
    public static Set<String> getNullPropertyNameSet(Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();
        Set<String> emptyNames = new HashSet<>();
        for (java.beans.PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null) emptyNames.add(pd.getName());
        }
        return emptyNames;
    }
}
이 방법 이 있 으 면 수정 할 때 비교적 편리 하 다.나의 방법 은 실체 류 에 방법 을 추가 하 는 것 이다.

    //     【    】 【   】    
    public void copy(Task task) {
        BeanCopyUtil.beanCopyWithIngore(task, this, "taskNum", "createPerson");
    }
그리고 service 에서 update 방법 으로 호출:

    @Transactional
    public Task updateTask(Task task) {
        try {
            if (task.getId() == null) {
                return null;
            }
            Task saveTask = taskRepository.findOne(task.getId());
            saveTask.copy(task);
            return taskRepository.saveAndFlush(task);
        } catch (Exception e) {
            throw new CustomException(SERVER_ERROR, e);
        }
    }
총결산
springboot 을 사용 할 때 매우 많은 주 해 를 만 날 수 있 습 니 다.이것 은 개발 에 많은 시간 을 절약 하고 의미 없 는 육체 노동 을 많이 하 는 것 입 니 다.그러나 주 해 를 사용 할 때 는 반드시 용도 와 용법 을 분명히 해 야 한다.그렇지 않 으 면 분명히 잘못 썼 다 고 생각 할 것 이다.
이상 은 개인 적 인 경험 이 므 로 여러분 에 게 참고 가 되 기 를 바 랍 니 다.여러분 들 도 저 희 를 많이 응원 해 주시 기 바 랍 니 다.

좋은 웹페이지 즐겨찾기