Scrivio Interview library
DebuggingIntermediate6 min read · updated 12 November 2026

Logging a JPA entity with log.info("{}", order) causes extra SQL queries and once a StackOverflowError. Why?

The entity's toString, usually generated by Lombok's @Data or @ToString or by an IDE, prints its associations. Printing a lazy association makes Hibernate load it, which is the extra SQL, or throws LazyInitializationException if no session is open. When the association is bidirectional, Order prints its lines and each line prints its Order, which prints the lines again, until StackOverflowError. The fix is to exclude associations from toString, print only IDs and simple fields, and log identifiers explicitly instead of whole entities.

Why this question is asked

Logging an object should never change what the application does, yet here a single log line runs database queries and, in one case, crashes the request. This is a very common JPA surprise, and interviewers like it because the explanation needs three pieces of knowledge at once: how lazy loading works, what generated toString methods do, and how logging calls toString. In this answer, we will recap lazy loading, reproduce both symptoms with a Lombok entity, follow the calls that cause the queries and the recursion, and then fix the entity and the logging habit.

1A Quick Recap of Lazy Loading

In JPA, an association such as an order's lines can be loaded lazily: Hibernate loads the Order row, and puts a placeholder where the lines would be. For a collection, the placeholder is a persistent collection wrapper; for a single related entity, it is a proxy, a generated subclass. The first time code touches the placeholder, for example by iterating the list or calling a getter on the proxy, Hibernate runs a query to load the real data. @OneToMany is lazy by default, and @ManyToOne is often made lazy explicitly for performance.

That loading needs an open persistence context, the session that loaded the entity. If the session is already closed, for example because the transaction ended in the service layer and we are now logging in a controller, touching the placeholder throws LazyInitializationException instead.

2Reproducing the Problem

Here is a typical pair of entities written with Lombok's @Data, which generates getters, setters, equals, hashCode and toString over all fields.

Java
@Entity @Data
class Order {
@Id private Long id;
private String status;
@OneToMany(mappedBy = "order") // lazy by default
private List<OrderLine> lines;
}
@Entity @Data
class OrderLine {
@Id private Long id;
private int quantity;
@ManyToOne(fetch = FetchType.LAZY)
private Order order; // points back to Order
}
Order order = orderRepository.findById(42L).orElseThrow();
log.info("{}", order);
// select ... from order_line where order_id=42 <- the extra SQL
// java.lang.StackOverflowError
// at Order.toString / OrderLine.toString / Order.toString ...

Notice that the log call has no explicit reference to lines at all. The parameterised message calls order.toString() when the INFO level is enabled, and the generated toString does the rest. This also explains why the problem may appear only in some environments: where INFO is disabled for that logger, toString never runs.

3Following the Calls

The generated Order.toString prints each field in turn. When it reaches lines, it calls the collection's toString, which must iterate the collection, so Hibernate initialises it with a query. Each OrderLine in turn prints its fields, including order, and Order.toString starts again, printing lines again, and so on. Nothing stops the loop, because neither class knows the other is already being printed, so the call stack grows until the JVM throws StackOverflowError.

Step throughWhat log.info("{}", order) really does
LoggerOrderHibernateOrderLine
toString()
touch lazy lines
select ... from order_line where order_id = 42
lines loaded
line.toString()
order.toString() again
line.toString() again
and again, until StackOverflowError

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

A single log line loads data and then recurses through the bidirectional link.

With a single unidirectional association, there is no recursion, but each log line still costs a query, and with N lines that each have lazy many-to-one links to other entities, one log line can turn into many queries. Outside a session, the first touch throws LazyInitializationException instead, with a message such as failed to lazily initialize a collection of role: Order.lines (the exact wording depends on your Hibernate version).

4Why Lombok Makes It So Easy

@Data and @ToString include every non-static field by default, and they are written once, when the class has three simple fields. Months later someone adds an association, and the toString, equals and hashCode silently grow to include it. @Data's generated equals and hashCode have the same recursion problem, so putting such an entity in a HashSet can also overflow the stack, and they violate the entity equality rule of using a stable key.

So the general advice is to avoid @Data and @EqualsAndHashCode on entities and use @Getter and @Setter instead, adding toString deliberately.

5Fix 1: Exclude Associations From toString

The entity's toString should print only its ID and simple fields. With Lombok, the safest form lists what is included rather than what is excluded, so new fields are left out by default.

Java
@Entity @Getter @Setter
@ToString(onlyExplicitlyIncluded = true)
class Order {
@Id @ToString.Include private Long id;
@ToString.Include private String status;
@OneToMany(mappedBy = "order") private List<OrderLine> lines; // not printed
}
// Without Lombok
@Override public String toString() {
return "Order[id=" + id + ", status=" + status + "]";
}
log.info("{}", order); // Order[id=42, status=PAID], and no query

If we want the child side to mention its parent, it should print the parent's ID. Be careful even then: calling getId() on a Hibernate proxy normally returns the ID without loading the entity, but other getters on the proxy do load it.

6Fix 2: Log Identifiers, Not Whole Entities

Even with a safe toString, logging whole entities is a habit worth breaking. It puts every printed field, possibly including personal data, into the logs, and it makes the log line's content depend on a method that someone may change. Logging the identifiers and the specific facts the line is about is clearer and cheaper.

Java
log.info("order {} moved to {}", order.getId(), order.getStatus());
// order 42 moved to PAID

Notice that this line also reads better: it says what happened, not just which object exists. Structured logging tools make this even more useful, because orderId becomes a searchable field.

7Follow-up questions

Would FetchType.EAGER fix it?

It would remove the LazyInitializationException, but it makes every load of Order fetch its lines, whether we need them or not, and it does nothing for the recursion. It trades a logging bug for a performance problem across the whole application.

Why did the debugger also trigger queries?

IDE debuggers call toString to display variables. With a toString that touches lazy associations, merely looking at an entity in the debugger runs queries, and the behaviour of the program under the debugger differs from normal runs. A toString that prints only simple fields avoids this.

Does the same apply to Jackson serialization of entities?

Yes, the same structure causes the same problems: serializing an entity with a bidirectional lazy association loads data and recurses. The usual fix there is not to serialize entities at all, but to map them to DTOs or records that contain exactly the fields the response needs.

8Conclusion

In this answer, we saw that logging an entity calls its toString, and that a generated toString, usually from Lombok's @Data or @ToString, prints lazy associations. Printing them makes Hibernate run queries, or throw LazyInitializationException without a session, and with a bidirectional association Order and OrderLine print each other until StackOverflowError. The fix is a toString that includes only the ID and simple fields, no @Data on entities, and log lines that print identifiers rather than whole entities.

What to say in the interviewAbout 70 seconds aloud

Open with

The log call itself is innocent: with a parameterised message, the logger calls order.toString() when INFO is enabled. The problem is the toString, which on entities is usually generated by Lombok's @Data or @ToString and includes every field, associations too.

Then, if they want more

The lines collection is lazy, so printing it makes Hibernate initialise it with a query, which is the extra SQL, or, if the session is already closed, throws LazyInitializationException.

And because the association is bidirectional, each OrderLine prints its order, which prints its lines again, and they recurse until StackOverflowError. @Data's equals and hashCode have the same recursion, so it is wrong on entities anyway.

The fix is to keep associations out of toString: use @Getter and @Setter with @ToString(onlyExplicitlyIncluded = true) and include just the ID and simple fields, or write toString by hand. On the child side, print the parent's ID, not the parent.

And as a habit, I log identifiers explicitly, like order {} moved to {} with the ID and status, rather than whole entities, which also keeps personal data out of the logs.

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 documentation below. 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 "Logging a JPA entity with log.info("{}", order) causes extra SQL queries and once a...": https://scrivio-interview-library.netlify.app/java/object-contracts/7186deba36/