簡體   English   中英

使用 spring 數據 jpa 更新單個字段

[英]Update single field using spring data jpa

我正在使用 spring-data 的存儲庫 - 非常方便,但我遇到了一個問題。 我可以輕松地更新整個實體,但我相信當我只需要更新一個字段時它毫無意義:

@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 return。

參考文檔中查看更多信息。

Hibernate 提供了 @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 T 實體和 @RequestBody 映射主體。 然后他們更新 body -> entity。

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();
            }
        }
    });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM