Contents
Hibernate
Working with a database through objects: entities, relationships, JPQL and Criteria queries, transactions.
1.Getting started
- What Hibernate isWhat ORM means, how the Jakarta Persistence standard and Hibernate relate, which versions the course uses and where Hibernate appears in Spring Boot.
- Project setupCreating a Maven project, adding Hibernate and H2 to pom.xml, configuring the connection in persistence.xml or in code, and the first run.
- The first entityHow to turn a Java class into a table: the @Entity, @Id and @GeneratedValue annotations, the requirements for an entity class and registering it in persistence.xml.
- EntityManager and the persistence contextWhat EntityManagerFactory and EntityManager are, how the persistence context tracks objects, why changes are saved without a save call, and how Session relates to EntityManager.
- Create, read, update, deleteThe four basic operations with entities: persist, find, changing a managed object, merge for objects from outside and remove.
- Entity statesThe four states of an entity object — transient, managed, detached and removed — how an object moves between them and why it matters.
2.Mapping entities
- Columns and typesConfiguring tables and columns with @Table and @Column, how Java types map to SQL types, storing enums with @Enumerated and dates, and excluding fields with @Transient.
- Embedded typesGrouping several columns into a value object with @Embeddable and @Embedded, using a record as an embedded type and renaming columns with @AttributeOverride.
- IdentifiersPrimary key generation strategies — SEQUENCE, IDENTITY and UUID — what allocationSize means, and natural identifiers with @NaturalId.
- InheritanceStoring a class hierarchy in tables: the SINGLE_TABLE, JOINED and TABLE_PER_CLASS strategies, polymorphic queries and common fields in a @MappedSuperclass.
- ValidationChecking entity fields with Jakarta Validation annotations: @NotBlank, @Size, @Email, automatic checks before saving and manual checks with Validator.
3.Relationships
- Many-to-one and one-to-manyLinking comments to a post with @ManyToOne and @JoinColumn, the reverse side with @OneToMany(mappedBy), and keeping both sides in sync with a helper method.
- One-to-oneLinking an author to a profile with @OneToOne: a unique foreign key on the owning side, mappedBy on the other side, and a shared primary key with @MapsId.
- Many-to-manyLinking posts and tags with @ManyToMany and a join table described by @JoinTable, helper methods for both sides, querying through the relationship and removing links.
- Cascading and orphan removalSaving and deleting a post together with its comments using cascade, the CascadeType values, and deleting comments removed from the list with orphanRemoval.
- Lazy and eager loadingWhen Hibernate loads related entities: FetchType.LAZY and EAGER, the default for each relationship type, proxy objects and LazyInitializationException.
- The N+1 problemWhy a list of posts with authors turns into dozens of queries, and three ways to fix it: join fetch, entity graphs and batch fetching.
4.Queries
- JPQL queriesThe Jakarta Persistence query language: selecting entities with createQuery, conditions and named parameters, sorting, getResultList, getSingleResult and getSingleResultOrNull.
- Joins, projections and bulk updatesMore JPQL: joining through relationships, selecting single fields, grouping with count and sum, building records with select new, and update and delete queries with executeUpdate.
- Criteria APIBuilding queries from Java objects with CriteriaBuilder: dynamic search filters, predicates, sorting, and the type-safe static metamodel generated by hibernate-processor.
- Native SQLRunning plain SQL through Hibernate with createNativeQuery: loading entities, reading rows as Object arrays, filling records, and parameters.
- PaginationSplitting query results into pages with setFirstResult and setMaxResults, counting pages, and how pagination works together with join fetch.
5.In a real project
- Transactions and flushingHow a resource-local transaction is begun, committed and rolled back, when Hibernate flushes changes to the database, automatic flush before queries and explicit em.flush().
- Optimistic lockingProtecting against lost updates with a @Version field: how the version check works in UPDATE, OptimisticLockException, and handling edits that come from a form.
- Schema generation and migrationsWhy drop-and-create is only for learning, the hibernate.hbm2ddl.auto values, generating a DDL script, Flyway migrations and checking the schema with validate.
- SQL logging and performanceLogging SQL and parameter values through Logback instead of show_sql, counting statements with Hibernate statistics, JDBC batching and a short list of performance habits.
- Second-level cacheA shared entity cache between EntityManagers: connecting JCache with Caffeine, marking entities with @Cacheable, checking hits with statistics and knowing what the cache does not cover.