繁体   English   中英

如何仅添加一个数据?

[英]how can add only one data?

@PutMapping("/api/cricketer/{id}")
public ResponseEntity<Cricketer> updateCricketer(@PathVariable("id") Long id, @RequestBody Cricketer cricketer) {
    Cricketer cCricketer = cricketerService.findById(id);
    cCricketer.setCountry(cricketer.getCountry());
    cCricketer.setName(cricketer.getName());
    cCricketer.setHighestScore(cricketer.getHighestScore());
    cricketerRepository.save(cCricketer);
    return new ResponseEntity<Cricketer>(cricketer, HttpStatus.OK);
}

大家好。 当我尝试更新updateCricketer方法上的数据时,它将按我输入的内容更新数据。 但是其他数据变为空。 有谁知道我该如何解决这个问题?

在设置值之前进行空检查。

@PutMapping("/api/cricketer/{id}")
public ResponseEntity<?> updateCricketer(@PathVariable("id") Long id, @RequestBody Cricketer cricketer) {
    Cricketer cCricketer = cricketerService.findById(id);
    if(Objects.nonNull(cCricketer)) {
        cCricketer.setCountry(Objects.isNull(cricketer.getCountry()) ? cCricketer.getCountry() : cricketer.getCountry());
        cCricketer.setName(Objects.isNull(cricketer.getName()) ? cCricketer.getName() : cricketer.getName());
        cCricketer.setHighestScore(Objects.isNull(cricketer.getHighestScore()) ? cCricketer.getHighestScore() : cricketer.getHighestScore());
        // Do same to the rest of the fields

        cricketerRepository.save(cCricketer);

        return new ResponseEntity<>(cricketer, HttpStatus.OK);
    } else {
        return new ResponseEntity<>("No cricketer Found!", HttpStatus.OK);
    }
}

对此的另一种解决方案是使用数据传输对象和对象映射器,这些映射器将根据您决定的策略执行空检查。

http://mapstruct.org/documentation/stable/reference/html/#mapping-result-for-null-arguments

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM