2017-05-28 21 views
-2

我有一個包含多個字段的實體類型。其中一些是對其他實體的引用。我想在Spring中創建一個Rest API端點,讓用戶可以更新這種類型的實體。更新僅傳入對象的非空屬性的實體

假設我有一個包含好友列表的實體User。我只想讓用戶更新用戶實體的某些特定字段,例如name,agedescription,而不是朋友列表。

此外,我只希望更新實體的那些屬性,使相應的傳入值不爲空。

public class UserController { 
    @RequestMapping(path="",method=RequestMethod.PUT) 
    public void update(@RequestBody User user) { 
     userService.save(user); 
    } 
} 

我該如何做到這一點?

回答

1

您可以採用DTO類,而不是將User對象作爲update()方法中的參數,而只能定義需要更改的屬性。

定義一個類UpdateUserDTO像這樣

public class UpdateUserDTO { 

    private String name; 
    private String description; 
    //other fields you want the clients to change. 
    ... 

} 

現在這個UpdateUserDTO可以在更新方法中使用作爲數據傳輸對象像這樣。

public class UserController { 

    @RequestMapping(path="",method=RequestMethod.PUT) 
    public void update(@RequestBody UpdateUserDTO dto) { 
     //validate your dto properties and then update your user entity. 
     userService.save(user); 
    } 

} 
0
Session session = sessionFactory.getCurrentSession(); 
String newuserId=newuser.getUserId(); 
session.clear(); 
User user=userService.readUser(newuserId); 
Property1 prop1=user.getProperty1(); 
List<Property2> prop2=user.getProperty2(); 
session.clear(); 
newuser.setProp1(prop1); 
newuser.setProp2(prop2); 
newuser.save(); //You should go through services and abstraction layers before saving aka it should be in the DAO implementation layer. 

你的問題需要改進,但嘗試這個答案。 您基本上將缺少的屬性保存在某些變量中,並將它們追加到您的前端用戶對象。 基於HQL輸出,它似乎像這樣獲取用戶並向其添加其他屬性。