🎯 What you will learn
Spring Data JPA is an abstraction layer on top of Hibernate (the JPA implementation) that turns your Java class into a database-backed entity with annotations, and generates all boilerplate CRUD SQL for you. By the end of this lesson you will understand:
@Entity,@Table,@Id,@GeneratedValue— the minimum ORM setup@Columnconstraints:nullable,unique,length,precision@ManyToOnewithFetchType.LAZYfor relationships@PrePersistlifecycle callbacks for audit fieldsJpaRepository<T,ID>: free findAll, findById, save, delete- Derived query methods — Spring generates SQL from the method name
@Querywith JPQL andnativeQuery=truefor custom SQLddl-autostrategies:create-dropfor dev,validate+ Flyway for production
🧾 Real-world scenario
Arjun maps the accounts and branches tables to Java classes in minutes with @Entity and @ManyToOne. Spring Data JPA generates all CRUD SQL automatically — findAll, findById, save, delete. No SQL boilerplate for the happy path.
🗂️ @Entity classes — Account + Branch
An entity is a Java class annotated with @Entity. Hibernate reads the annotations and maps each field to a column. @Id marks the primary key; @GeneratedValue(IDENTITY) tells the database to auto-increment it. @ManyToOne with FetchType.LAZY maps the foreign key relationship to a Branch object without loading it immediately.
@JsonIgnoreProperties: Hibernate proxies for LAZY associations contain internal fields like hibernateLazyInitializer. Without this annotation Jackson will try to serialise them and throw an error. Add it to every @Entity class you expose via REST.
🚀 JpaRepository + derived query methods
Extend JpaRepository<Account, Long> and you instantly get findAll(), findById(), save(), deleteById(), and count() — zero implementation code. Declare a method starting with findBy and Spring Data generates the SQL at startup from the method name.
Derived query magic: Spring Data parses findByAccountNo into SELECT ... FROM accounts WHERE account_no = ? at startup — not at runtime. If the method name references a field that doesn't exist on the entity, the application fails to start, giving you compile-time-like safety.
🔍 @Query — high-value accounts
JPQL (Jakarta Persistence Query Language) uses entity class names and field names instead of table/column names — making queries database-agnostic. Hibernate translates JPQL to the dialect of your target database at startup. For database-specific syntax use nativeQuery = true.
📋 ddl-auto strategies
| ddl-auto value | What it does | Use in |
|---|---|---|
create-drop | Creates schema on startup; drops on shutdown | Local dev, unit tests |
create | Creates schema on startup; keeps data on shutdown | Integration tests |
update | Adds missing columns; never drops | Early dev (use carefully) |
validate | Validates schema against entities; no changes | Production (use Flyway/Liquibase) |
none | Disables all schema management | When schema is managed externally |
Production rule: Always use validate (or none) in production. Run schema migrations with Flyway (V1__create_schema.sql in src/main/resources/db/migration/). Never use create or create-drop on a live database.
🎤 Interview Q&A
findAll(), findById(id), save(entity), deleteById(id), existsById(id), count(). These cover all basic CRUD without a line of SQL. JpaRepository extends CrudRepository and PagingAndSortingRepository.
A lifecycle callback. The annotated method runs just before the entity is saved to the database for the first time (INSERT). Use it to set audit fields like createdAt automatically.
LAZY: fetch the related entity only when the field is accessed — avoids N+1 queries for collections. EAGER: always fetch the related entity in the same query. Default: @ManyToOne is EAGER, @OneToMany is LAZY. Prefer LAZY + explicit joins in @Query for performance.
Add spring-boot-starter-flyway or spring-boot-starter-liquibase to pom.xml. Place migration scripts in src/main/resources/db/migration/ (for Flyway: V1__create_schema.sql). Set spring.jpa.hibernate.ddl-auto=validate and Spring Boot runs migrations on startup.
Spring uses JDK dynamic proxies (for interfaces extending Repository). At startup the JpaRepositoryFactory creates a SimpleJpaRepository<T,ID> instance bound to the EntityManager. For query methods Spring parses the method name into a JPQL AST, compiles it to SQL once, and caches the PreparedStatement. Custom @Query methods are compiled and cached the same way.
📝 Quiz — 5 questions
@GeneratedValue(strategy = GenerationType.IDENTITY) do?findByAccountNo(String) do in a JpaRepository interface?spring.jpa.hibernate.ddl-auto=create-drop do?Next: Relationships and Queries — @OneToMany, JOIN FETCH →
⚠️ Common mistakes
validate in production and manage schema with Flyway/Liquibase.@JsonIgnoreProperties({"hibernateLazyInitializer","handler"}) to the entity, or use DTOs.findAll() then .stream().filter(). Push predicates into the database with derived queries or @Query — the DB is orders of magnitude faster than filtering millions of rows in the JVM.SELECT a FROM Account a JOIN FETCH a.branch.✅ Key takeaways
- @Entity + @Id + @GeneratedValue = a database-backed Java class in ~10 lines
- JpaRepository provides findAll/findById/save/delete with zero SQL
- Derived query methods (findByXxx) generate SQL from the method name
- @Query with JPQL for custom queries; nativeQuery=true for DB-specific SQL
- Use ddl-auto=validate + Flyway in production; create-drop for local dev only
From JPA basics to a production database layer
Join the Best AI Programs — three 5-month courses, fully online, with placement assistance. Week 1 is free.
Explore our AI-era courses →