1

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"
                 }
}

1 Answer 1

4

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();
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much, man! I've been trying to get this to work for the past 4 hours, and never tought of this as a solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.