🎯 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
  • @Column constraints: nullable, unique, length, precision
  • @ManyToOne with FetchType.LAZY for relationships
  • @PrePersist lifecycle callbacks for audit fields
  • JpaRepository<T,ID>: free findAll, findById, save, delete
  • Derived query methods — Spring generates SQL from the method name
  • @Query with JPQL and nativeQuery=true for custom SQL
  • ddl-auto strategies: create-drop for dev, validate + Flyway for production
💼 Interview reality: "@Entity vs @Table", "LAZY vs EAGER fetch", and "explain the N+1 query problem" appear in virtually every Spring Boot backend interview. Understand how Hibernate generates SQL from your annotations before you walk into the room.

🧾 Real-world scenario

🏦
Real-world scenario · SouthBank India (Mumbai)
Object–relational mapping for the account ledger

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.

mvn spring-boot:run
Account.javaLesson 28 · @Entity, @Id, @Column, @ManyToOne, @PrePersist
startup output — JPA schema created
:: Spring Boot :: (v3.3.5) INFO --- SouthbankApplication : Started SouthbankApplication in 1.72 seconds

@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.

curl -s http://localhost:8766/api/accounts
AccountRepository.javaLesson 28 · JpaRepository, derived queries, @Query JPQL + native
verified output — JpaRepository.findAll()
[ { "id": 1, "accountNo": "SB-100001", "holderName": "Arjun Sharma", "balance": 85000.0, "accountType": "SAVINGS", "branch": { "id": 1, "code": "MUM01", "city": "Mumbai", "region": "Maharashtra" }, "createdAt": "2026-04-26T21:01:16.582733" }, { "id": 2, "accountNo": "SB-100002", "holderName": "Priya Mehta", "balance": 210000.0, "accountType": "CURRENT", "branch": { "id": 1, "code": "MUM01", "city": "Mumbai", "region": "Maharashtra" }, "createdAt": "2026-04-26T21:01:16.582733" }, { "id": 3, "accountNo": "SB-100003", "holderName": "Vikram Singh", "balance": 47500.0, "accountType": "SAVINGS", "branch": { "id": 2, "code": "DEL01", "city": "Delhi", "region": "Delhi" }, "createdAt": "2026-04-26T21:01:16.582733" }, { "id": 4, "accountNo": "SB-100004", "holderName": "Deepa Nair", "balance": 125000.0, "accountType": "SAVINGS", "branch": { "id": 3, "code": "BLR01", "city": "Bangalore", "region": "Karnataka" }, "createdAt": "2026-04-26T21:01:16.582733" } ]

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.

curl -s "http://localhost:8766/api/accounts/high-value?min=100000"
AccountRepository.java + generated SQLLesson 28 · JPQL @Query + Hibernate-generated SQL
verified output — accounts with balance ≥ ₹1,00,000
[ { "id": 2, "accountNo": "SB-100002", "holderName": "Priya Mehta", "balance": 210000.0, "accountType": "CURRENT", "branch": { "id": 1, "code": "MUM01", "city": "Mumbai", "region": "Maharashtra" }, "createdAt": "2026-04-26T21:01:16.582733" }, { "id": 4, "accountNo": "SB-100004", "holderName": "Deepa Nair", "balance": 125000.0, "accountType": "SAVINGS", "branch": { "id": 3, "code": "BLR01", "city": "Bangalore", "region": "Karnataka" }, "createdAt": "2026-04-26T21:01:16.582733" } ]

📋 ddl-auto strategies

ddl-auto valueWhat it doesUse in
create-dropCreates schema on startup; drops on shutdownLocal dev, unit tests
createCreates schema on startup; keeps data on shutdownIntegration tests
updateAdds missing columns; never dropsEarly dev (use carefully)
validateValidates schema against entities; no changesProduction (use Flyway/Liquibase)
noneDisables all schema managementWhen 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

EasyWhat methods does JpaRepository provide for free?
+

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.

EasyWhat is @PrePersist?
+

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.

MediumWhen should you use FetchType.LAZY vs EAGER?
+

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.

MediumHow do you run Flyway or Liquibase migrations instead of ddl-auto?
+

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.

HardHow does Spring Data JPA generate implementation classes at runtime?
+

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

Question 1 of 5
What annotation marks a Java class as a database table?
Question 2 of 5
What does @GeneratedValue(strategy = GenerationType.IDENTITY) do?
Question 3 of 5
What does findByAccountNo(String) do in a JpaRepository interface?
Question 4 of 5
What is the difference between JPQL and native SQL in @Query?
Question 5 of 5
What does spring.jpa.hibernate.ddl-auto=create-drop do?
0
/ 5
Quiz complete!

Next: Relationships and Queries — @OneToMany, JOIN FETCH →

⚠️ Common mistakes

Using ddl-auto=create in production
This drops and recreates all tables on every restart — destroying all data. Set validate in production and manage schema with Flyway/Liquibase.
Serializing LAZY entities without @JsonIgnoreProperties
When Jackson tries to serialise a LAZY association outside a transaction, Hibernate throws LazyInitializationException. Fix: add @JsonIgnoreProperties({"hibernateLazyInitializer","handler"}) to the entity, or use DTOs.
Calling findAll() and filtering in Java
Never do 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.
N+1 query problem
Loading a list of accounts and then accessing each account's branch triggers one extra SELECT per account. Fix with JOIN FETCH in JPQL: 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
Africa & India's Best AI Academy
🤖 AI-first 🎓 Placement Assistance

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 →