How Hibernate Works

The Main Building Blocks

JPA nameHibernate nameWhat it isHow many
EntityManagerFactorySessionFactoryHeavy object built at startup from your config and entity classesOne per database
EntityManagerSessionLightweight unit of work; holds the persistence contextOne per request / transaction
EntityTransactionTransactionBegin / commit / rollbackOne at a time per EntityManager
Persistence contextFirst-level cacheMap of entities currently managed by the EntityManagerOne 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 closed

Hibernate 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 row

Generated SQL

With SQL logging turned on (see the Setup module) you can watch it:

# console output at commit

Example output

Hibernate: insert into product (category,description,name,price,stock) values (?,?,?,?,?)
Hibernate: update product set category=?,description=?,name=?,price=?,stock=? where id=?