IonuČ› Zamfir IonuČ› Zamfir -4 years ago 146
JSON Question

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.

One of my POJOs looks like this:

@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:

{
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: 1,
name: "Product 1",
manufacturer_id: 1
manufacturer: {
id: 1,
name: "Manufacturer 1"
}
}

Answer Source

You can just add an additional getter to ProductModel and make them @Transient

@JsonProperty("manufacturer_id")
@Transient
public Long getManufacturerId() {
  return manufacturer == null ? null : manufacturer.getId();
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download