【问题标题】:Spring boot with spring data jpa. How can i perform partial update of entity from request body?带有弹簧数据 jpa 的弹簧启动。如何从请求正文执行实体的部分更新?
【发布时间】:2016-03-15 13:59:55
【问题描述】:

基本上,我有带有更新方法的 REST 控制器类。

 @RequestMapping(value = "{id}", method = RequestMethod.POST)
public Account update(@PathVariable Integer id, @RequestBody Account account){
     .....
}

当请求正文只有 Account 对象的部分字段时,如何执行给定 id 的 account 对象的部分更新?

【问题讨论】:

    标签: java spring spring-boot spring-data


    【解决方案1】:

    你可以通过 id 获取吗?拥有原始版本后,如果定义了属性,您可以使用新对象对其进行更新?比如:

    @RequestMapping(value = "{id}", method = RequestMethod.POST)
    public Account update(@PathVariable Integer id, @RequestBody Account account){
        Account acc = dao.getById(id);
        acc.copy(account);
        dao.update(acc);
    }
    
    class Account {
         ....
        public void copy(final Account account) {
             if (account.prop1 != null) {
                 this.prop1 = account.prop1;
             }
             // update the mutable fields
             .....
        }
    }
    

    【讨论】:

    • 感谢您的建议!基本上,我想要一些高级弹簧方法(即 accountDao.mergeNonNull(acc, account),我不知道 :))有这样的东西吗?
    • 我不知道,抱歉。
    猜你喜欢
    • 2014-03-28
    • 1970-01-01
    • 2017-01-04
    • 2018-02-14
    • 2020-11-11
    • 1970-01-01
    • 2020-04-09
    • 2015-01-22
    • 2018-09-08
    相关资源
    最近更新 更多