All modules

Module 7 · Build

Database & Spring Data JPA

Model entities honestly, choose fetch strategies deliberately, and keep every write inside a transaction scoped to one business operation.

Foundation17 chapters450 minutesPrerequisite: Application architecture and SQL fundamentals
Start module

Chapter plan

What you will complete

01The JPA EcosystemJDBC speaks SQL, JPA defines the object-relational contract, Hibernate implements it, and Spring Data repositories sit on top—each layer has its own documentation and its own levers.JDBCHibernateSpring Data JPA 15 min02Database Migrations with FlywayVersioned SQL scripts turn schema changes into reviewed, repeatable artifacts—Hibernate validates, Flyway evolves.Write versioned migrations that run once, in order, everywhereKeep ddl-auto at validate so code never improvises schemaPlan forward-only changes for zero-downtime deploys 20 min03Entity Modeling@Entity, @Id, @Column, and @Version map a class to a table; identifier strategy and schema ownership are decisions, not defaults to accept.@Entity@IdGenerationType 20 min04The Persistence Context & Entity LifecycleTrack an entity through transient, managed, detached, and removed states, and see why dirty checking—not your setters—writes changes.Explain what the persistence context stores and when it flushesDistinguish managed from detached entities before mutating themKeep state transitions inside entities instead of setter calls 25 min05Spring Data RepositoriesExtending JpaRepository yields CRUD, pagination, and flushing with no implementation class—Spring Data backs the interface with a proxy at startup.JpaRepositoryCrudRepositoryPagingAndSortingRepository 15 min06Derived Query MethodsMethod names like findBySkuIgnoreCase compile into queries at startup; the parser rejects typos and unknown properties before the app ever serves a request.Method NamingfindByPagination 20 min07@Query and JPQL@Query writes JPQL against your entity model, or native SQL against tables when a vendor feature earns its portability cost.@QueryJPQLNative SQL 20 min08Entity Relationships@ManyToOne owns the foreign key and @OneToMany(mappedBy) mirrors it; bidirectional object graphs need helper methods to stay consistent.@OneToMany@ManyToOnemappedBy 30 min09Cascade Types & Orphan RemovalCascade propagates lifecycle operations along an association; orphan removal deletes children that leave the collection—both belong only inside one aggregate.Cascade PERSIST and REMOVE only from parent to owned childrenUse orphanRemoval for lines that cannot exist without their orderKeep both sides of a bidirectional link in sync through methods 25 min10Composite Keys & EmbeddablesSome rows are identified by two columns together—model that identity with @EmbeddedId and reusable @Embeddable value objects.Define identity with an @Embeddable id recordQuery composite keys through derived id-part methodsRecognize when a surrogate key serves better than a composite one 20 min11Entity Inheritance Strategies@Inheritance maps Java hierarchies to tables three ways; each trades normalization against query cost, and switching later is a migration.Compare SINGLE_TABLE, JOINED, and TABLE_PER_CLASS honestlyUse discriminator columns to tell subtypes apartPick per hierarchy from measured queries, not habit 25 min12The N+1 Query ProblemOne query for the list plus one per row for each association is N+1; fetch joins, entity graphs, or batch sizing collapse it back to a handful of queries.N+1 ProblemFetchType.LAZYJOIN FETCH 25 min13Transactions (@Transactional)@Transactional wraps a method in one atomic unit; rollback defaults cover only unchecked exceptions—a default that quietly commits checked-exception flows.@TransactionalRollback RulesPropagation 20 min14Propagation & Isolation in PracticePropagation decides whether a method joins the caller’s transaction or starts its own; isolation decides which concurrent anomalies remain visible.Choose REQUIRED, REQUIRES_NEW, and SUPPORTED deliberatelyExplain read phenomena from READ_UNCOMMITTED to SERIALIZABLEKeep audit writes alive when the business transaction rolls back 30 min15Locking, Indexes & Query PlansOptimistic @Version detects conflicts after the fact; pessimistic locks prevent them outright—and neither compensates for a query plan scanning the table.Add @Version and handle OptimisticLockingFailureException with bounded retriesReserve hot rows with pessimistic write locks only when contention is realRead EXPLAIN output before creating or blaming indexes 35 min16Projections, Specifications & AuditingBuild efficient read models, compose optional search filters, and capture creation/update timestamps without exposing managed entities.DTO ProjectionsJpaSpecificationExecutorJPA Auditing 30 min17Complete JPA Implementation: Product Catalog APIModule capstone · Multi-file buildConnect every JPA concept in a production-shaped, multi-file implementation and understand why each boundary exists.Vertical SliceDesign RationaleIntegration Verification 75 min

Module outcome

Persist and query data without N+1 surprises, leaked entities, or accidental multi-statement commits.

Mental model

Spring Data JPA writes the boilerplate SQL, but you must still understand the underlying relational model and transaction boundaries.

Module checkpoint

Production Product Catalog API

Build one complete vertical slice with migrations, entities, repositories, query choices, transactional services, DTO mapping, REST endpoints, and real-database tests.

  • CRUD, search, pagination, and stock updates work through HTTP
  • Flyway owns the schema and Hibernate only validates it
  • Repository tests run against PostgreSQL with Testcontainers
  • Read paths return DTOs without N+1 queries or entity leakage

Final module assessment

Ready to prove mastery?

Complete all 50 questions after finishing the module lessons and checkpoint.

Take module quiz