Video in progress

Strong Middle 🐻 Hibernate and JPA

When you call `order.getCustomer().getId()`, does the lazy proxy get initialized, meaning does SQL go out?

No, usually it doesn't: the proxy holds the id itself and returns it from the identifier getter without initializing. Any other getter (getName()) does trigger a SELECT. This behavior is true only when a proxy is in use; if it came from find() or the association is EAGER, the full object is already loaded.

📖 Answer

@Transactional(readOnly = true)
public List<Long> customerIds(List<Long> orderIds) {
    return orderRepo.findAllById(orderIds).stream()
        .map(o -> o.getCustomer().getId())   // no SQL on the customer table
        .toList();
}

For a @ManyToOne(fetch = LAZY), Hibernate takes the customer_id column from the order row and builds a proxy with that id. The proxy has the id, so getId() doesn't hit the database. getName() runs select ... from customer where id = ?.

This behavior is quite useful in practice: for example, when checking permissions, order.getCustomer().getId().equals(currentUserId) doesn't produce an extra query. Outside a transaction, getId() doesn't throw LazyInitializationException either.

Where it can mislead you:

  • the method has to be the identifier getter. Another getter such as getCustomerCode() triggers initialization even if it returns the id;
  • if hibernate.jpa.compliance.proxy=true is on, then under the strict JPA requirement any method (including getId()) opens the proxy;
  • if equals()/toString() touch other fields, those get opened.

If in doubt, check with Hibernate.isInitialized(order.getCustomer()) or look at the SQL log. If you need only the id, some teams also add an extra @Column(name = "customer_id", insertable = false, updatable = false) Long customerId to the entity, which is even more explicit.