Hibernate
Hibernate is an ORM that implements JPA and adds its own APIs. A Session (or EntityManager) tracks entities, generates SQL, and flushes changes on commit.
Detailed Explanation
Hibernate predates JPA and still has features JPA does not standardize: @BatchSize, @Fetch, Hibernate types, bytecode enhancement, and a native Session. In a Spring Boot app you usually stay on JPA annotations and let Hibernate be the provider (spring.jpa.hibernate.ddl-auto is a Hibernate property).
The persistence context is Hibernate's identity map. Dirty checking compares current field values to the snapshot and writes UPDATEs. That is convenient and surprising: mutating a loaded entity is enough to schedule a write. Session.evict and clear drop tracking. stateless sessions skip it for batches.
Dialects generate SQL per database. ddl-auto=update in production is a risk; use Flyway or Liquibase. Show-sql and a formatter belong in dev. A statement inspector or p6spy shows bind values.
You reach for Hibernate when JPA is your mapping story. You reach for the native Session for batch or unwrap. You reach for JDBC when Hibernate's SQL is the bug.
The cost of open-in-view (the Spring default in older Boot versions) is lazy loads in the view layer and hidden N+1. Turn it off. The cost of CascadeType.ALL is deletes you did not mean. The cost of a bidirectional relation without a owning side is extra UPDATEs.
Second-level cache is optional and easy to stale. First-level cache is per session and always on.
A typical leak of understanding is save versus dirty checking. Beginners call save on every field change. Hibernate already knows the instance is managed and will write it. Extra save/merge calls on managed entities do not make the flush safer; they make the session harder to read. For batch imports, a stateful session plus dirty checking can explode memory: flush and clear in chunks, or use a stateless session and JDBC batches. Read the SQL log once for each use case you ship. If you cannot explain a statement, change the mapping or write the query yourself.
Code Examples
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
@Entity
class Item {
@Id
Long id;
String name;
}import org.hibernate.Session;
public class Native {
static Item load(Session session, long id) {
return session.get(Item.class, id);
}
}Common Gotchas
`open-in-view=true` hides N+1 in the view
disable it and fetch explicitly.
`ddl-auto=create` drops data
never in production.