Python中文网

一个关于 编程问题的解答网站.

有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用Spring Boot的java请求包装器主体

我有两个实体代表数据库中的两个表,类似于继承的概念:

实体人:

@Entity
@Table(name ="person", schema = "myself")
public class Person implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="person_id")
    private long id;

    @Column(name = "person_name", nullable = false, length = 255)
    @NotNull(message = "name_expects")
    private String name;

    @OneToOne(mappedBy = "person", cascade = CascadeType.ALL, orphanRemoval = false, fetch = FetchType.LAZY)
    @JsonIgnore
    private AdressPerson adressPerson;

... get and setters
}

实体地址:

@Entity
@Table(name ="adress_person", schema = "myself")
public class AdressPerson implements Serializable {

    @Id
    @Column(name = "person_id")
    private long id;

    @Column(name = "type", nullable = false, length = 14)
    private String type;

    @Column(name = "adress", nullable = false, length = 255)
    private String adress;

    @OneToOne(fetch = FetchType.LAZY)
    @MapsId
    private Person person;

... get and setters
}

我需要发送一个单独的请求帖子和表单数据:

{
   "id":1,
   "name":"John Doe",
   "type": "home",
   "adress" : "Madison Ave"
}

在我的控制器中,我需要以这种方式接收:

...
@PostMapping(value = "", consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE}, produces = {MediaType.APPLICATION_JSON_VALUE})
public AdressPerson addAdressPerson(@NotNull @RequestParam AdressPerson adressPersonRequest)  {
    //code
}
...

然而,我无法进行映射,我曾尝试使用filter和RequestWrapper,但无法覆盖消息体。有人能帮我吗

谢谢


共 (2) 个答案

  1. # 1 楼答案

    Spring的@RequestParam映射查询参数,比如?name=something&address=some-address

    当您试图发出POST请求并希望将JSON请求负载反序列化为java类时

    改用@RequestBody

  2. # 2 楼答案

    在@RestController类中,可以按如下方式定义POST映射方法:

    ...
    @PostMapping(value = "")
    public AdressPerson addPerson(@RequestBody Person person)  {
           //code
    }
    ...
    

    默认情况下,spring boot项目需要/返回一个JSON主体,因此可以省略consumes和Products属性

    现在,为了在上面的控制器中接收有效负载,JSON请求主体应该如下所示:

    {
      "id":1,
      "name":"John Doe",
      adressPerson": {
          "type": "home",
          "adress" : "Madison Ave"
       }
    }
    

    此外,在实体Person中,从addressperson字段中删除@JsonIgnore,而尝试使用@JsonManagedReference和@JsonBackReference