programing

스프링 데이터 jpa를 사용하여 단일 필드 업데이트

css3 2023. 7. 29. 08:46

스프링 데이터 jpa를 사용하여 단일 필드 업데이트

저는 스프링 데이터의 저장소를 매우 편리하게 사용하고 있지만 문제에 직면했습니다.전체 엔티티를 쉽게 업데이트할 수 있지만 단일 필드만 업데이트해야 하는 경우에는 의미가 없다고 생각합니다.

@Entity
@Table(schema = "processors", name = "ear_attachment")
public class EARAttachment {

    private Long id;
    private String originalName;
    private String uniqueName;//yyyy-mm-dd-GUID-originalName
    private long size;
    private EARAttachmentStatus status;

업데이트하려면 메서드 저장을 호출합니다.로그에 다음이 표시됩니다.

batching 1 statements: 1: update processors.ear_attachment set message_id=100, 
original_name='40022530424.dat', 
size=506, 
status=2,
unique_name='2014-12-16-8cf74a74-e7f3-40d8-a1fb-393c2a806847-40022530424.dat'
where id=1 

저는 다음과 같은 것을 보고 싶습니다.

batching 1 statements: 1: update processors.ear_attachment set status=2 where id=1 

Spring의 저장소에는 이름 규칙을 사용하여 무언가를 선택할 수 있는 많은 기능이 있습니다. 아마도 updateForStatus(int status)와 같은 업데이트와 유사한 기능이 있을 수 있습니다.

리포지토리 인터페이스에서 다음과 같은 작업을 시도할 수 있습니다.

@Modifying
@Query("update EARAttachment ear set ear.status = ?1 where ear.id = ?2")
int setStatusForEARAttachment(Integer status, Long id);

다음과 같은 명명된 매개 변수를 사용할 수도 있습니다.

@Modifying
@Query("update EARAttachment ear set ear.status = :status where ear.id = :id")
int setStatusForEARAttachment(@Param("status") Integer status, @Param("id") Long id);

int 반환 값은 업데이트된 행 수입니다.다음을 사용할 수도 있습니다.void돌아가다.

참조 설명서에서 자세히 참조하십시오.

최대 절전 모드는 @DynamicUpdate 주석을 제공합니다.엔티티 수준에서 이 주석을 추가하기만 하면 됩니다.

@Entity(name = "EARAttachment ")
@Table(name = "EARAttachment ")
@DynamicUpdate
public class EARAttachment {
    //Code omitted for brevity
}

이제 사용할 때EARAttachment.setStatus(value)그리고 "CrudRepository"를 실행합니다.save(S entity)특정 필드만 업데이트합니다. 예를 들어 다음 UPDATE 문이 실행됩니다.

UPDATE EARAttachment 
SET    status = 12,
WHERE  id = 1

데이터 바인딩을 사용하여 @PathVariable 엔티티 및 @RequestBodyMap 본문을 매핑할 수 있습니다.그리고 그들은 본문 -> 실체를 업데이트합니다.

public static void applyChanges(Object entity, Map<String, Object> map, String[] ignoreFields) {
    map.forEach((key, value) -> {
        if(!Arrays.asList(ignoreFields).contains(key)) {
            try {
                Method getMethod = entity.getClass().getMethod(getMethodNameByPrefix("get", key));
                Method setMethod = entity.getClass().getMethod(getMethodNameByPrefix("set", key), getMethod.getReturnType());
                setMethod.invoke(entity, value);
            } catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
                e.printStackTrace();
            }
        }
    });
}

언급URL : https://stackoverflow.com/questions/29202277/update-single-field-using-spring-data-jpa