spring 如何通过JSON在POST请求中只发送Id外键?

olhwl3o2  于 2023-04-10  发布在  Spring
关注(0)|答案(1)|浏览(171)

我做网上鞋店,现在我为它的商品创建REST控制器,所以现在我正在测试POST请求,我与制造商的制造商有关系,制造商ID为

,但现在我需要将制造商的所有信息写入JSON,但我认为这不是一个好的做法。
良好实体:

@Entity
@Table(name = "goods")
public class Good {
    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    //@JsonIgnore
    private int id;

    @Column(name = "Title")
    private String title;

//    @Enumerated(EnumType.STRING)
//    @Column(name = "sex")
//    private sexType sexType;

    @Column(name = "sex")
    private String sex;

    /**
     * proved and it actually works!
     */
    //@JsonManagedReference
    @ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.DETACH,
    CascadeType.REFRESH, CascadeType.MERGE})
    @JoinColumn(name = "ManufacturerId")
    //@JsonIgnoreProperties
    Manufacturer manufacturer; //Many goods can refer to one manufacturer

    @JsonManagedReference
    @OneToMany(cascade = {CascadeType.PERSIST, CascadeType.DETACH,
            CascadeType.REFRESH, CascadeType.MERGE}, mappedBy = "good")//Uni-directional reference to size array
    List<Size> sizes;

制造商实体:

@Entity
@Table(name = "manufacturers")
public class Manufacturer {
    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @Column(name = "ManufacturerName")
    private String manufacturerName;

    @Column(name = "Address")
    private String address;

    @Column(name = "Telephone")
    private String telephone;

    //@JsonBackReference
    @OneToMany(cascade = {CascadeType.PERSIST, CascadeType.DETACH,
            CascadeType.REFRESH, CascadeType.MERGE},
            mappedBy = "manufacturer")
    @JsonIgnore
    private List<Good> goods;

POST请求的JSON示例:

{
    "title": "Model",
    "sex": "CHILD",
    "manufacturer": {
      "id": 1,
      "manufacturerName": "Ralf",
      "address": "Moscow",
      "telephone": "9-999-999-99-99"
    },
    "sizes": [
      {
        "size": 37,
        "quantity": 5
      },
      {
        "size": 39,
        "quantity": 4
      }
    ]
  }

如何仅发送制造商ID?
如果我使用@JsonIgnore注解,我想我不会获得有关制造商的其他信息

z31licg0

z31licg01#

尝试使用hateoas实现链接。这里是一个示例请求数据。

{
"title": "Model",
"sex": "CHILD",
"manufacturer": 
            "_links": {
            "self": {
                "href": "/manufacturers/1"
            }
        },
"sizes": [
  {
    "size": 37,
    "quantity": 5
  },
  {
    "size": 39,
    "quantity": 4
  }
]

}现在不需要在请求数据中提供所有Manufacturer字段,而是只需要提供id/

相关问题