Fix Jackson Infinite Recursion With Bidirectional Entities
Stop the StackOverflowError that Jackson raises when entities reference each other, by returning DTOs, or by breaking the cycle with Jackson annotations.

A bidirectional JPA mapping is two references that point at each other: an order knows its customer, and a customer knows its orders. Hand that object graph to Jackson and it follows the first reference, then the second, then the first again, until the stack is exhausted. The error is dramatic and easy to recognise, and the right fix is a matter of what your API should return in the first place. This post explains why it happens, ranks the fixes from best to worst, and covers the Hibernate-proxy variant that looks similar. It applies to Spring Boot with Jackson; the annotations are the same in Jackson 2 and Jackson 3.
com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion (StackOverflowError)
(through reference chain: dev.javahacks.Customer["orders"]->java.util.ArrayList[0]
->dev.javahacks.Order["customer"]->dev.javahacks.Customer["orders"]->...)The reference chain in the message is the diagnosis. It names the cycle: Customer.orders to Order.customer and back.
The entities
@Entity
class Customer {
@Id Long id;
String name;
@OneToMany(mappedBy = "customer") List<Order> orders;
}
@Entity
class Order {
@Id Long id;
@ManyToOne Customer customer;
}A controller that returns a Customer gives Jackson a graph with a loop. It has no way to know where to stop, because serialisation is a straightforward walk over the getters.
Fix 1, the best: return DTOs
record OrderSummary(Long id, String status) { }
record CustomerView(Long id, String name, List<OrderSummary> orders) { }
@GetMapping("/customers/{id}")
CustomerView get(@PathVariable Long id) {
Customer c = customers.findWithOrders(id);
return new CustomerView(c.getId(), c.getName(),
c.getOrders().stream().map(o -> new OrderSummary(o.getId(), o.getStatus())).toList());
}A DTO has exactly the fields you decided to publish and no back reference, so no cycle can exist. It also decouples the API from the database model: renaming a column or adding a lazy association no longer changes the JSON or breaks a client. Exposing entities directly leaks internals and invites the lazy-loading problems described below. The few lines of mapping code are a small price. The surrounding design is covered in building a REST API with Spring MVC.
Fix 2: ignore one side
@OneToMany(mappedBy = "customer")
@JsonIgnore
List<Order> orders;@JsonIgnore removes the property from serialisation and deserialisation. The cycle is gone, and so is the data: a customer never shows its orders. That is acceptable if no client needs them, and wrong when one does. Use it when one direction is irrelevant to the API.
Fix 3: managed and back references
@OneToMany(mappedBy = "customer")
@JsonManagedReference
List<Order> orders;
@ManyToOne
@JsonBackReference
Customer customer;The managed side is serialised normally and the back side is omitted. On deserialisation Jackson restores the link, setting order.customer for each order read in the list. The output of an order alone omits its customer, so a client that fetches an order cannot see who owns it, which limits the usefulness. It also supports exactly one pair per type, and mixing several back references to the same class needs names.
Fix 4: identity
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
@Entity
class Customer { ... }With identity information, the first time an object is serialised it appears in full, and later references to it become just its id. The cycle is cut with a reference. The output is valid, and clients must resolve the references, which no ordinary REST client expects. Use it for internal data exchange between components that share the convention, not for a public API.
The Hibernate proxy variant
A related failure comes from lazy loading. A lazy association is a Hibernate proxy, and Jackson tries to serialise the proxy's internals:
No serializer found for class org.hibernate.proxy.pojo.bytebuddy.ByteBuddyInterceptorOr, if the session has already closed, a LazyInitializationException appears when Jackson calls the getter; see that exception. Both are symptoms of serialising entities. DTOs fix them. If you must serialise entities, the jackson-datatype-hibernate module understands proxies and skips uninitialised ones, and fetching what you need before the response is written avoids the lazy load, using the techniques in fixing N+1.
Also check toString, equals and hashCode
The same loop can hide elsewhere. A toString() generated by an IDE or Lombok that prints every field recurses through the two references, and the stack overflow appears in a log line or a debugger, not in the controller. A generated hashCode that includes the collection on one side has the same problem, and worse, it changes as the collection changes. Exclude the back reference from all three. An entity's identity should come from its id or a business key, and its toString should print scalars only. Lombok's @ToString.Exclude and @EqualsAndHashCode.Exclude do it declaratively.
Choosing
| Situation | Fix |
|---|---|
| A public API | DTOs |
| One direction is never needed | @JsonIgnore on it |
| Both directions are needed in a nested document | @JsonManagedReference and @JsonBackReference |
| Internal exchange of a graph with shared nodes | @JsonIdentityInfo |
A test that keeps the cycle from coming back
Cycles return when someone adds a back reference to a class that used to be flat, and the first time anybody notices is a production stack overflow. Add a serialisation test for every type the API returns. It takes the object through the same ObjectMapper the application uses and asserts on the JSON:
@Test
void customerSerialisesWithoutLooping() throws Exception {
Customer customer = new Customer(1L, "Ada");
Order order = new Order(10L, customer);
customer.getOrders().add(order);
String json = objectMapper.writeValueAsString(CustomerView.of(customer));
assertThat(json).contains("\"orders\"").doesNotContain("\"customer\"");
}Inject the mapper from the Spring context with @JsonTest or @SpringBootTest, so the test uses the real configuration and modules. The test is cheap, it pins the shape of the response, and when a developer maps a new association into the DTO they have to touch the test and think about the cycle. If your API returns many types, a parametrised test that builds each response object with a back reference and serialises it covers all of them at once.
Deserialisation has the same problem in reverse
The cycle matters on the way in as well. A client that posts a customer with nested orders, each carrying its customer, produces an object graph that must be wired together correctly. With DTOs, the mapping code builds the entities and sets both sides of the association with the helper methods, which keeps the in-memory model consistent, as described in owning and inverse sides. With @JsonManagedReference, Jackson sets the back reference for you, which is convenient and easy to get wrong when the nesting is more than one level deep. Another reason to take a DTO as input: a client should never be able to set the id or the version of an entity by including them in a payload.
When the entity is simple enough
A small internal tool that returns entities with no back references does not need DTOs, and adding them there is ceremony. The moment a relationship becomes bidirectional, or the API has outside clients, switch. Spring Boot's JSON handling is described in the reference, and the annotations are listed in the Jackson annotations wiki. The mapping that creates the cycle is explained in the Hibernate and JPA guide.


