【发布时间】:2020-02-20 01:49:13
【问题描述】:
我正在尝试实现一个非常基本的 Spring Boot Web 应用程序。我在 @RequestBody 的帮助下将 JSON 对象映射到实体(如客户实体)。
在 addCustomer 方法中,我只想绑定/映射 firstName 和 lastName 字段并忽略 Id字段,即使客户端响应 JSON 具有该字段。
在 updateCustomer 方法中,我需要映射包括 Id 在内的所有字段,因为我需要 Id 字段来更新实体。
如何在@RequestBody的自动映射过程中忽略一些或一个字段。
@RestController
@RequestMapping("/customer-service")
public class CustomerController {
@Autowired
CustomerServiceImpl customerService;
//This method has to ignore "id" field in mapping to newCustomer
@PostMapping(path = "/addCustomer")
public void addCustomer(@RequestBody Customer newCustomer) {
customerService.saveCustomer(newCustomer);
}
//This method has to include "id" field as well to updatedCustomer
@PostMapping(path = "/updateCustomer")
public void updateCustomer(@RequestBody Customer updatedCustomer) {
customerService.updateCustomer(updatedCustomer);
}
}
@Entity
@Table(name = "CUSTOMER")
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long cusId;
private String firstName;
private String lastName;
//Default Constructor and getter-setter methods after here
}
【问题讨论】:
标签: spring-boot jackson spring-restcontroller