Aki*_*pun 0 jackson spring-boot spring-restcontroller
我正在尝试实现一个非常基本的 Spring Boot Web 应用程序。我在@RequestBody.
在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);
}
}
Run Code Online (Sandbox Code Playgroud)
@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
}
Run Code Online (Sandbox Code Playgroud)
您可以使用多个@JsonViews 在每个方法中使用不同的映射。
public class Views {
public static class Create {
}
}
Run Code Online (Sandbox Code Playgroud)
@Entity
@Table(name = "CUSTOMER")
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long cusId;
@JsonView(Views.Create.class)
private String firstName;
@JsonView(Views.Create.class)
private String lastName;
...
}
Run Code Online (Sandbox Code Playgroud)
@PostMapping(path = "/addCustomer")
public void addCustomer(@RequestBody @JsonView(Views.Create.class) Customer newCustomer) {
customerService.saveCustomer(newCustomer);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4771 次 |
| 最近记录: |