Spring boot JPA - JSON without a nested object with OneToMany relation

I have a project that deals with some ORM object mapping (there are some @OneToMany relationships, etc.).

I use the REST interface to handle these objects and Spring JPA to manage them in the API.

This is an example of one of my POJOs:

 @Entity public class Flight { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String name; private String dateOfDeparture; private double distance; private double price; private int seats; @ManyToOne(fetch = FetchType.EAGER) private Destination fromDestination; @ManyToOne(fetch = FetchType.EAGER) private Destination toDestination; @OneToMany(fetch = FetchType.EAGER, mappedBy = "flight") private List<Reservation> reservations; } 

When executing the request, I must specify everything in JSON:

 { "id": 0, "reservations": [ {} ], "name": "string", "dateOfDeparture": "string", "distance": 0, "price": 0, "seats": 0, "from": { "id": 0, "name": "string" }, "to": { "id": 0, "name": "string" } } 

What would I prefer, it actually indicates the identifier of the reference object instead of all its bodies, for example:

 { "id": 0, "reservations": [ {} ], "name": "string", "dateOfDeparture": "string", "distance": 0, "price": 0, "seats": 0, "from": 1, "to": 2 } 

Is it possible? Can someone give me some idea on how to do this? I only find tutorials on how to do the opposite (the solution that I already have).

+6
source share
2 answers

Yes it is possible.

For this purpose you should use a couple of Jackson annotations for your entity model:

 @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id") @JsonIdentityReference(alwaysAsId = true) protected Location from; 

Your serialized JSON will look instead:

 { "from": { "id": 3, "description": "New-York" } } 

like this:

 { "from": 3 } 

As stated in the official documentation:

@JsonIdentityReference - an optional annotation that can be used to configure details of the reference to objects for which the "Identity Object" (see JsonIdentityInfo )

alwaysAsId = true used as a marker to indicate whether all value references should be serialized as identifiers (true);

Note , if true is used, deserialization may require additional contextual information and, possibly, the use of a custom resolver identifier - the default processing may be insufficient.

+15
source

You can ignore your JSON content using the @JsonIgnore annotation. In the field you want to hide in your JSON, you can mark this with @JsonIgnore . You can change your JSON as follows:

 { "id": 0, "reservations": [ {} ], "name": "string", "dateOfDeparture": "string", "distance": 0, "price": 0, "seats": 0, "from": { "id": 0 }, "to": { "id": 0 } } 

But you may not like the following:

 { "id": 0, "reservations": [ {} ], "name": "string", "dateOfDeparture": "string", "distance": 0, "price": 0, "seats": 0, "from": 0, "to": 1 } 
+2
source

All Articles