【问题标题】:How to update only few fields of entity using JPA and Hibernate?如何使用 JPA 和 Hibernate 仅更新实体的少数字段?
【发布时间】:2020-01-03 11:02:01
【问题描述】:

我正在使用 MySQL 数据库。

我的表格实体是具有以下字段的帐户:

id(long), balance (double), created_on(Date), currency(Enum). 

当我发出 PUT 请求来更新帐户时,我会传入请求正文 JSON。

例如,我想只更新余额,但要保存其他列的值。 在这种情况下(我没有传递货币类型)余额会更新,但货币的值为 NULL。那是因为它是枚举吗?

我尝试过使用@DynamicUpdate 注解,但仍然没有任何变化。

@RestController 
public class AccountController { 

    @PutMapping("/accounts/{id}") 
    public void updateAccount(\@PathVariable long id, @RequestBody AccountDto accountDto) { 
       accountService.updateAccount(id, accountDto); 
    } 
} 

我正在使用 AccountDto(我在请求正文中传递)并且我正在调用 accountService

public void updateAccount(long id, AccountDto accountDto) { 
    Account account = accountRepository.getOne(id); 
    account.fromDto(accountDto); 
    this.accountRepository.save(account); }), 

调用AccountRepository

public void fromDto(AccountDto accountDto) { 
   this.balance = accountDto.getBalance(); 
   this.currency = accountDto.getCurrency(); 
} 

这是 AccountDto 类:

public class AccountDto { 
    private long id; 

   @NotNull @PositiveOrZero 
   private double balance; 

   @NotNull @Enumerated(EnumType.STRING) 
   private Currency currency; 
}

【问题讨论】:

  • @DynamicUpdate 不是解决方案,因为它仅用于创建最小更新(仅更新已更改的列)。能否展示 RestController 的代码以及如何更新实体?
  • \@RestController public class AccountController { \@PutMapping("/accounts/{id}") public void updateAccount(\@PathVariable long id, \@RequestBody AccountDto accountDto) { accountService.updateAccount(id , 帐户Dto);我正在使用 AccountDto (我在请求正文中传递)并且我正在调用 accountService ( public void updateAccount(long id, AccountDto accountDto) { Account account = accountRepository.getOne(id); account.fromDto(accountDto ); this.accountRepository.save(account); }),调用AccountRepository。
  • account.fromDto(accountDto); 是做什么的做?请显示代码,但不要将其作为评论发布,将其添加到问题中
  • public void fromDto(AccountDto accountDto) { this.balance = accountDto.getBalance(); this.currency = accountDto.getCurrency();这里是 AccountDto 类: public class AccountDto { private long id; \@NotNull \@PositiveOrZero 私人双余额; \@NotNull \@Enumerated(EnumType.STRING) 私有货币货币; }

标签: mysql spring jpa enums


【解决方案1】:

您需要对 Account 实体执行选择查询,然后只更新所需的字段。 (例如,我自己假设用于访问数据库的底层方法

public updateAccount(AccountModel jsonBody) {
Account entity = accountRepository.findById(jsonBody.getAccountId());
entity.setBalance(jsonBody.getBalance());
accountRepository.save(entity);
}

【讨论】:

    【解决方案2】:

    如果您在 JSON 中获得 null 作为货币,则不应更新它:

    所以 fromDto 必须是这样的:

    public void fromDto(AccountDto accountDto) { 
       this.balance = accountDto.getBalance(); 
    
       if (accountDto.getCurrency() != null) {
           this.currency = accountDto.getCurrency(); 
       }
    } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-15
      • 1970-01-01
      • 2012-12-28
      • 2022-09-28
      相关资源
      最近更新 更多