Careeroza
How Hibernate Works
The Main Building Blocks
| JPA name | Hibernate name | What it is | How many |
|---|---|---|---|
EntityManagerFactory | SessionFactory | Heavy object built at startup from your config and entity classes | One per database |
EntityManager | Session | Lightweight unit of work; holds the persistence context | One per request / transaction |
EntityTransaction | Transaction | Begin / commit / rollback | One at a time per EntityManager |
| Persistence context | First-level cache | Map of entities currently managed by the EntityManager | One per EntityManager |
What Happens on Startup and on a Request
STARTUP (once)
application.yml / persistence.xml + @Entity classes
|
v
EntityManagerFactory (SessionFactory)
- reads mappings, validates them
- picks the SQL dialect (MySQL, PostgreSQL, H2 ...)
- opens a connection pool (HikariCP in Spring Boot)
- optionally creates/updates tables (ddl-auto)
EACH REQUEST / TRANSACTION
EntityManager opened -> begin transaction
find / persist / change fields / remove
(entities tracked in the persistence context)
commit -> flush: Hibernate generates INSERT/UPDATE/DELETE
-> JDBC sends SQL -> database
EntityManager closedHibernate Writes the SQL
Product p = new Product("Boat Rockerz 450", new BigDecimal("1499.00"), 120);
entityManager.persist(p); // no SQL written by you
p.setStock(119); // just change the field...
// ...at commit Hibernate notices the change and updates the rowGenerated SQL
With SQL logging turned on (see the Setup module) you can watch it:
# console output at commitExample output
Hibernate: insert into product (category,description,name,price,stock) values (?,?,?,?,?) Hibernate: update product set category=?,description=?,name=?,price=?,stock=? where id=?