亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Spring Boot 上的基本放置(更新)

Spring Boot 上的基本放置(更新)

江戶川亂折騰 2021-09-29 17:07:25
我想要一些非?;镜臇|西。我只想更新用戶。前端為用戶發送一個json。 我想避免設置 currentUser 的每個值(它有 50 個字段)@PutMapping("user/{id}")public boolean updateUser(@PathVariable id, @RequestBody User user) {   User currentUser = userRepo.findOne(id);   // What now??}
查看完整描述

3 回答

?
交互式愛情

TA貢獻1712條經驗 獲得超3個贊

你需要做這樣的事情。請記住,這種方法有助于部分對象更新。這意味著如果您的對象(在 RequestBody 中)不包含某些字段(field==null),那么該字段將保持不變。


@PutMapping("user/{id}")

public boolean updateUser(@PathVariable id, @RequestBody User user) {

   User currentUser = userRepo.findOne(id);

   user = (User) PersistenceUtils.partialUpdate(currentUser, user);

   return userRepo.save(user);


}


public class PersistenceUtils {


    public static Object partialUpdate(Object dbObject, Object partialUpdateObject){

        String[] ignoredProperties = getNullPropertyNames(partialUpdateObject);

        BeanUtils.copyProperties(partialUpdateObject, dbObject, ignoredProperties);

        return dbObject;

    }


    private static String[] getNullPropertyNames(Object object) {

        final BeanWrapper wrappedSource = new BeanWrapperImpl(object);

        return Stream.of(wrappedSource.getPropertyDescriptors())

                .map(FeatureDescriptor::getName)

                .filter(propertyName -> wrappedSource.getPropertyValue(propertyName) == null)

                .toArray(String[]::new);

    }



}


查看完整回答
反對 回復 2021-09-29
?
慕森王

TA貢獻1777條經驗 獲得超3個贊

你可以參考這個關于 PATCH vs PUT 的問題。


假設您只是在更改用戶的在線狀態。在這種情況下,最好使用 PATCH 并將更改反映在路徑變量上。


例如:


@PatchMapping("user/{id}/{status}")

public boolean setStatus(@PathVariable id, @PathVariable status) {

   User currentUser = userRepo.findOne(id);

   currentUser.setStatus(status);

   userRepo.save(currentUser);

   // ...

}

如果打算對未定義數量的字段進行更改,您可以使用 PUT,在請求正文中包含數據并使用 DTO 模式。你可以在網上找到很多關于 DTO 模式的例子。在這種情況下,代碼如下。


@PatchMapping("user/{id}")

public boolean updateUser(@PathVariable id, @RequestBody UserDTO userDTO) {


   // UserMapper is the mapper class which returns you a new User

   // populated with the data provided in the data transfer object.

   User user = UserMapper.makeUser(userDTO);

   userRepo.update(id, user);

   // ...

}


查看完整回答
反對 回復 2021-09-29
  • 3 回答
  • 0 關注
  • 194 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號