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

How to limit fields that map in @RequestBody

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

的帮助下将 JSON 对象映射到实体(说客户实体)

addCustomer 方法中,我只想 bind/map 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
}

TL;DR:使用以下之一:

  • @JsonIgnoreProperties("fieldname") 在你的 class.
  • @JsonIgnore 在您的字段上忽略其映射。

示例:

@Getter
@Setter
@JsonIgnoreProperties("custId")
public class Customer {

@JsonIgnore
private String custId;
private String firstName;
private String lastName;

}

但是,由于您有相同的 POJO,它将跳过两个请求的 "custId" 映射。

AFAIK,您不应该收到 @PostMapping(添加客户)的 custId 值,因此它将被动态设置为 null 或默认值。并且在创建用户的同时,您还应该为其创建 ID 或者让数据库来处理它。

对于 @PutMapping(更新用户),您必须获取可用于识别用户的 ID 值,然后进行更新。

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

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