如何限制@RequestBody中映射的字段

Aki*_*pun 0 jackson spring-boot spring-restcontroller

我正在尝试实现一个非常基本的 Spring Boot Web 应用程序。我在@RequestBody.

addCustomer方法中,我只想绑定/映射firstNamelastName字段并忽略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)

Mac*_*iak 7

您可以使用多个@JsonViews 在每个方法中使用不同的映射。

  1. 定义视图:
public class Views {
    public static class Create {
    }
}
Run Code Online (Sandbox Code Playgroud)
  1. 选择每个视图中应使用哪些字段:
@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)
  1. 告诉 Spring MVC 在特定方法中使用此视图:
@PostMapping(path = "/addCustomer")
public void addCustomer(@RequestBody @JsonView(Views.Create.class) Customer newCustomer) {
    customerService.saveCustomer(newCustomer);
}
Run Code Online (Sandbox Code Playgroud)