Issue
I have a Vote and a Restaurant entities, when I manage their relations with
@JsonBackReference
and @JsonManagedReference
I have a problem.
If I serialize Restaurant - everything seems to be fine.
If I serialize Vote - fields with @JsonManagedReference
are omitted. And I have this JSON:
{
"id": 50,
"voteDate": "2021-08-04"
}
I would appreciate if you could tell me, how I can serialize both objects without omitting fields and getting StackOverflow
error.
Some entity's code are omitted for brevity:
@Entity
public class Vote extends AbstractBaseEntity {
@ManyToOne
@JsonBackReference
private Restaurant restaurant;
private LocalDate voteDate;
@ManyToOne(fetch = FetchType.LAZY)
@JsonBackReference
private User user;
}
@Entity
@Getter
@Setter
@NoArgsConstructor
@ToString(exclude = {"votes", "dishes"})
public class Restaurant extends AbstractNamedEntity {
String address;
@OneToMany(mappedBy = "restaurant", cascade = CascadeType.ALL, orphanRemoval = true)
@JsonManagedReference
private List<Dish> dishes;
@OneToMany(mappedBy = "restaurant", cascade = CascadeType.ALL, orphanRemoval = true)
@JsonManagedReference
private List<Vote> votes;
}
Solution
You have to convert entities to DTO objects. Add postfix Entity
to the entities. And use names without postfix for DTO.
@Entity
class VoteEntity {
}
class Vote {
private String voteDate;
private String restaurantName;
}
Convert entities to DTO on the service level and do the serialization after that.
Answered By - v.ladynev