Video in progress

Strong Junior 🐻 Hibernate and JPA

What problems come up if you return an entity directly as a REST response (through Jackson)?

Jackson calls the getters and opens up lazy associations: you get either LazyInitializationException or a hidden N+1, and with a bidirectional association, infinite recursion. On top of that, your API contract gets tied to the database and internal fields leak out.

📖 Answer

@GetMapping("/orders/{id}")
public Order get(@PathVariable Long id) {
    return repo.findById(id).orElseThrow();   // the problems start here
}

What can happen:

  • With open-in-view=false, serialization happens after the transaction, so opening the order.getCustomer() proxy throws LazyInitializationException.
  • With open-in-view=true there's no error, but Jackson opens every lazy collection. On a list endpoint that means hundreds of queries.
  • Order.items → OrderItem.order → Order again...: StackOverflowError or an "Infinite recursion" error.
  • The Hibernate proxy's internal fields (hibernateLazyInitializer) end up in serialization, and Jackson throws an error.
  • If a field like passwordHash is added to the entity, it automatically leaks into the API.

You can paper over the symptoms with @JsonIgnore, @JsonManagedReference or the jackson-datatype-hibernate module, but the main problem remains: every change in the database breaks the API.

That's why I return a separate DTO for the response (often a record) and build it inside the transaction:

public record OrderView(Long id, String number, BigDecimal total) {}

At first glance this is extra code, but it lets the API and the database change independently.