Video in progress
Why does a bidirectional relationship cause infinite recursion when you return an entity directly as JSON?
Jackson writes Order and moves into items, from each item back into order, and the loop never stops, ending in a StackOverflowError or a depth error. The cleanest fix is to return a DTO, not the entity.
📖 Answer
@Entity class Order {
@OneToMany(mappedBy = "order") List<OrderItem> items;
}
@Entity class OrderItem {
@ManyToOne Order order;
}
Order -> items[0] -> order -> items[0] -> order -> ... Jackson calls the getter every time, and there's no end. The log usually shows StackOverflowError or HttpMessageNotWritableException.
An extra problem: when Jackson touches a lazy collection, you get either LazyInitializationException or (with open-in-view on) hidden SELECTs while the response is being written.
The solutions, from worst to best:
@JsonIgnore: remove one side from the JSON;@JsonManagedReference/@JsonBackReference: the parent side is written, and the reference on the child side is skipped;- a DTO: you spell out exactly what the API looks like:
record OrderDto(Long id, List<ItemDto> items) {
static OrderDto from(Order o) {
return new OrderDto(o.getId(), o.getItems().stream().map(ItemDto::from).toList());
}
}
Jackson annotations help quickly, but they tie the persistence model to the API format. If you add a new field to the entity, it automatically leaks into the API, sometimes together with a password hash.
Sign up to mark studied questions and save your progress.