【发布时间】:2019-08-04 08:24:25
【问题描述】:
我使用 RestController 更新数据到 db 但我有问题。当我更新值时,如果我的更新值为 null ,它总是将数据更新到 db 为 null。我不想要它。如果我的请求中有 1 个值为 null 的字段,我不想更新它。
下面是我的代码:
控制器:
休息控制器
@RequestMapping("/api/products")
@Api(value = "ProductControllerApi",produces = MediaType.APPLICATION_JSON_VALUE)
public class ProductController {
@Autowired
private ProductService productService;
@PatchMapping("/{id}")
public ResponseEntity<ProductResDto> updateProduct(@RequestBody ProductReqDto productReqDto, @PathVariable String id) {
return ResponseEntity.ok(productService.updateProduct(product,id));
}
ProductReqDto:
public class ProductReqDto {
private String name;
private String type;
private String category;
private String description;
private Double prince;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Double getPrince() {
return prince;
}
public void setPrince(Double prince) {
this.prince = prince;
}
}
ProductResDto:
public class ProductResDto {
private String name;
private String type;
private String category;
private Double prince;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Double getPrince() {
return prince;
}
public void setPrince(Double prince) {
this.prince = prince;
}
}
MappingDto:
private ProductDto convertToProductDto(ProductReq product) {
return modelMapper.map(product, ProductResDto.class);
}
我如何处理方法 convertToProductDto 只映射值不为空。因为如果,映射一个字段:example:product_name = null,它插入到db null。我想要如果字段 ProductReq 有值,它映射并保留数据库中的其他不同字段(如果不包含来自 ProductReq 的值,则不要将其设置为 null)。 示例:
**ReqProductDto.class**
private String name;
private String type;
private String category;
private String description;
private Double prince;
但如果用户只更新两个字段:
private String name;
private String type;
我想要 spring 更新字段 name 和字段 type 用户输入并在我的数据库中保留 category,description,prince。在我的情况下,如果用户更新两个字段:name 和字段 type,spring 更新它但 spring set category,description,prince 为 null在我的数据库中。我不想要它。 请帮助我,谢谢。
【问题讨论】:
-
所以如果任何字段是
null你不想更新?或者更新有值的字段而不更新null字段,你在找哪一个? -
我有更新问题。请帮忙
-
您如何将这些数据保存到数据库中?你在用 spring-jpa 使用休眠吗?
-
没有。我使用 TypeQuery 和写更新方法看起来像:objectdb.com/java/jpa/query/api .
标签: java spring spring-boot mapping dto