简体   繁体   English

Spring Boot JPA-具有嵌套对象和ID的json

[英]Spring boot JPA - json with nested object and id

I am trying to do a project with some basic ORM relationships and REST controllers for sending jsons. 我正在尝试使用一些基本的ORM关系和REST控制器来发送json的项目。

One of my POJOs looks like this: 我的一个POJO如下所示:

@Entity
@Table(name = "product_models")
public class ProductModel extends BaseEntityWithName {
  @ManyToOne(fetch = FetchType.EAGER)
  @JoinColumn(name = "manufacturer_id")
  @JsonManagedReference
  private ProductManufacturer manufacturer;

  --constr + setters + getters--

}

When making get requests, the response looks something like this: 发出get请求时,响应如下所示:

{ 
  id: 1, 
  name: "Product 1", 
  manufacturer: {
                   id: 1, 
                   name: "Manufacturer 1"
                 }
}

Is there any way to get the request look something like this?(Return both the foreign key id and the nested object) 有什么办法可以使请求看起来像这样?(同时返回外键ID和嵌套对象)

{ 
  id: 1, 
  name: "Product 1", 
  manufacturer_id: 1
  manufacturer: {
                   id: 1, 
                   name: "Manufacturer 1"
                 }
}

You can just add an additional getter to ProductModel and make them @Transient 您可以向ProductModel添加一个额外的getter并将其设置为@Transient

@JsonProperty("manufacturer_id")
@Transient
public Long getManufacturerId() {
  return manufacturer == null ? null : manufacturer.getId();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM