Video in progress
What happens in Hibernate if you make an entity class or its fields `final`?
Hibernate can't create a proxy subclass of a final class, so a lazy @ManyToOne in practice loads immediately. The JPA specification forbids final fields: Hibernate tries to fill them through reflection, but you can't rely on that.
📖 Answer
For a lazy association, Hibernate generates a proxy that subclasses your class (using ByteBuddy). If the class is final, it can't be subclassed:
@Entity
public final class Customer { ... } // no proxy can be created
@Entity
public class Order {
@ManyToOne(fetch = FetchType.LAZY)
private Customer customer; // declared LAZY, but...
}
Hibernate logs a warning at startup and fetches Customer immediately when Order is loaded. getReference(Customer.class, id) also runs a full SELECT instead of returning a proxy. There's no error, just unexpected queries in the SQL log.
The same applies to final getter and setter methods: the proxy can't override them, so when the method is called, an empty field can come back without initialization.
final fields are a different problem: the persistent fields of a JPA entity must not be final, because Hibernate creates the object with the no-arg constructor and then fills in the fields. In some cases reflection manages it, but that is behavior outside the specification.
That's why, when you write entities in Kotlin, you add the kotlin-jpa and allopen plugins, which make classes open automatically. In Java it's enough not to make the entity final and to get immutability by hiding the setters.
Sign up to mark studied questions and save your progress.