Scrivio Interview library
DebuggingFoundations6 min read · updated 12 November 2026

An entity Order with @Data has a @OneToMany List<OrderLine> lines, and OrderLine has @ManyToOne Order order, also with @Data. Logging an order throws StackOverflowError. Why, and what other problems does @Data cause on entities?

Lombok's generated toString on Order prints its lines, each OrderLine's toString prints its order, which prints its lines again, and the recursion never ends until the stack overflows; equals and hashCode recurse the same way. @Data on entities also makes toString trigger lazy loading or LazyInitializationException, and makes hashCode depend on mutable fields and the generated id, which breaks Sets of entities after persist. The fix is @Getter and @Setter only, associations excluded with @ToString.Exclude, hand-written id-based equals with a constant hashCode, and a protected no-args constructor for JPA.

Why this question is asked

This is one of the first serious Lombok bugs many Spring developers meet: a harmless log line, log.debug("Saving {}", order), crashes the request with StackOverflowError. Interviewers ask it because the answer shows whether we understand both what Lombok generates and how JPA relationships and proxies behave. In this answer, we will recap bidirectional associations, reproduce the error, follow the recursion, look at the other problems @Data causes on entities, and then write the entity the right way.

1A Quick Recap of Bidirectional Associations

In JPA, Order and OrderLine are related in both directions: Order has a @OneToMany list of lines, and each OrderLine has a @ManyToOne reference back to its order. That is useful for navigation in both directions, but it means the object graph contains a cycle: order -> line -> order -> line and so on. Any code that walks the graph without stopping at objects it has already visited will loop forever.

Lombok's generated toString, equals and hashCode are exactly that kind of code. They visit every field, and for a field that is an object, they call that object's toString, equals or hashCode.

2Reproducing the Error

Here are the two entities with @Data and the line that fails.

Java
@Entity @Data
public class Order {
@Id @GeneratedValue private Long id;
@OneToMany(mappedBy = "order", cascade = CascadeType.ALL)
private List<OrderLine> lines = new ArrayList<>();
}
@Entity @Data
public class OrderLine {
@Id @GeneratedValue private Long id;
@ManyToOne(fetch = FetchType.LAZY) private Order order;
private int quantity;
}
Order order = new Order();
OrderLine line = new OrderLine();
line.setOrder(order);
order.getLines().add(line);
log.info("Saving {}", order);
// java.lang.StackOverflowError
// at OrderLine.toString(OrderLine.java)
// at java.lang.String.valueOf(String.java)
// at Order.toString(Order.java)
// at java.lang.String.valueOf(String.java)
// at OrderLine.toString(OrderLine.java) ...
Step throughThe recursion in toString
LoggerOrderOrderLine
toString()
lines -> line.toString()
order -> order.toString()
lines -> line.toString()
order -> order.toString() ... until StackOverflowError

5 messages in order. Play them, or step through them one at a time.

Each object prints the other, forever.

The stack trace alternates between the two toString methods, which is the signature of this bug. The same happens if we put either object into a HashSet, because hashCode recurses in the same way, and when we compare two orders with equals.

3Other Problems @Data Causes on Entities

Even without a cycle, toString on entities is dangerous. Printing a lazy association, such as order.getLines() or line.getOrder() marked LAZY, makes Hibernate load it from the database just to write a log line, which can mean hidden queries in a loop. Outside a transaction, with the session closed, it throws LazyInitializationException instead. So a debug log statement can either slow the request down or crash it.

equals and hashCode cause subtler bugs. They use all fields, including the generated id and mutable fields. A new order has id null; after persist the id is set, so its hashCode changes. An entity added to a HashSet before saving cannot be found or removed from that set afterwards. Hibernate itself keeps entities in sets in some places, and collections mapped as Set suffer the same way. And equals over all fields means two objects representing the same row compare unequal when one has a changed field, which is not what entity identity means.

Finally, @Data generates setters for every field, including the id. And these classes still have the no-args constructor JPA needs only because they declare no constructors; adding @Builder or @AllArgsConstructor later would silently remove it.

What @Data generates and what it does on an entity
GeneratedProblem on an entity
toString over all fieldsinfinite recursion; lazy loading or LazyInitializationException
hashCode over all fieldschanges after persist and on edits; Sets break
equals over all fieldssame row compares unequal; recursion through associations
Setters for all fieldsid and associations changed freely

4Writing the Entity the Right Way

We keep Lombok for what is harmless, getters and selected setters, and write the rest deliberately. Associations are excluded from toString. equals compares the id when it exists and treats different objects without an id as different, and hashCode is a constant per class, so it never changes when the id is assigned. A protected no-args constructor satisfies JPA.

Java
@Entity
@Getter
@Setter
@ToString
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class Order {
@Id @GeneratedValue
@Setter(AccessLevel.NONE)
private Long id;
@OneToMany(mappedBy = "order", cascade = CascadeType.ALL)
@ToString.Exclude
private List<OrderLine> lines = new ArrayList<>();
@Override
public final boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Order other)) return false;
return id != null && id.equals(other.getId());
}
@Override
public final int hashCode() { return Order.class.hashCode(); } // constant: safe across persist
}
log.info("Saving {}", order); // Order(id=null)

OrderLine gets the same treatment, with @ToString.Exclude on its order field. Notice that we read other.getId() rather than other.id, because the other object may be a Hibernate proxy whose fields are not filled in. A fuller version of this equals also unwraps Hibernate proxies when comparing classes; the important parts are id-only comparison and a constant hashCode.

5Follow-up questions

Why is a constant hashCode acceptable?

Because entity sets are usually small, a constant hash only puts all of them into one bucket, which costs little. In exchange, the hash never changes when the id is assigned at persist, so an entity can be added to a set before it is saved and still be found afterwards. Correctness matters more here than a perfect spread of hash codes.

Can I use @EqualsAndHashCode with onlyExplicitlyIncluded on the id?

It is better than @Data, but its hashCode still changes from the null id to the real id when the entity is saved, and its class check does not account for proxies. For entities, the hand-written version is safer.

Is @ToString.Exclude enough to stop lazy loading in logs?

For the associations we exclude, yes. Any lazy field still included will load when printed, so the rule is to keep toString to simple columns such as the id and a few plain attributes.

6Conclusion

In this answer, we saw that @Data on two entities with a bidirectional association produces toString, equals and hashCode that call each other forever, which is why logging an order throws StackOverflowError. We also saw that @Data's toString triggers lazy loading or LazyInitializationException, and that its hashCode over mutable fields and the generated id breaks Sets after persist. The fix is @Getter and chosen @Setter, @ToString.Exclude on associations, hand-written id-based equals with a constant hashCode, and @NoArgsConstructor(access = AccessLevel.PROTECTED) for JPA.

What to say in the interviewAbout 90 seconds aloud

Open with

The StackOverflowError comes from the cycle in the object graph. Order has a list of lines and each OrderLine points back to its order. @Data generates toString over all fields, so Order's toString prints its lines, each line's toString prints its order, which prints its lines again, and so on until the stack overflows.

Then, if they want more

You can see it in the stack trace alternating between the two toString methods. equals and hashCode recurse the same way, so putting an order in a HashSet fails too. @Data causes more problems on entities. toString touches lazy associations, so a log line can trigger database queries or throw LazyInitializationException after the session is closed. hashCode uses all fields including the generated id, so it changes after persist, and an entity added to a Set before saving cannot be found afterwards.

And it generates setters for the id and every association. My fix is to drop @Data on entities.

I use @Getter and selected @Setter, exclude associations from toString with @ToString.Exclude, and write equals and hashCode myself: equals compares the id only when it is not null, reading it through the getter because of proxies, and hashCode returns a constant per class, so it is stable across persist. A natural key also works if it never changes. And I add @NoArgsConstructor with protected access, which JPA needs.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "An entity Order with @Data has a @OneToMany List<OrderLine> lines, and OrderLine has...": https://scrivio-interview-library.netlify.app/java/lombok/e3c14bb35b/