Practice: ORM and JPA setup
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Every task here comes back to two questions: which layer does this job (JPA, Hibernate, Spring Data JPA or the database), and what does the startup log say when the setup is wrong. Answer both and you can debug JPA calmly.
Matching each job to JPA, Hibernate or Spring Data JPA
Sort any job by asking who owns it. Example 1 lists the starter's main jars, each from its own library.
Example 1 · Who brings what: the JPA starter's main jars
Runs in: the jpa-lab Spring Boot project
mvn dependency:tree$ mvn dependency:tree
...
[INFO] | | \- com.zaxxer:HikariCP:jar:7.0.2:compile
[INFO] | | | | \- jakarta.persistence:jakarta.persistence-api:jar:3.2.0:compile
[INFO] | | | +- org.hibernate.orm:hibernate-core:jar:7.4.5.Final:compile
[INFO] | | | \- org.springframework:spring-orm:jar:7.0.9:compile
[INFO] | | +- org.springframework.data:spring-data-jpa:jar:4.1.1:compile
[INFO] \- com.mysql:mysql-connector-j:jar:9.7.0:runtime
...What this code does
HikariCParrives through the JDBC starter: the pool, not part of JPA.jakarta.persistence-apiis JPA (interfaces and annotations only),hibernate-coreis the provider, andspring-ormconnects Spring to it.spring-data-jpais the repository layer;mysql-connector-jis the driver, needed only at runtime.
JPA owns the rules and names: @Entity, @Id, @Column, EntityManager, JPQL. Hibernate does the work: reads the mapping, writes and runs SQL, validates the schema, logs statements. Spring Data JPA owns repositories: JpaRepository, method names like findByNameIgnoreCase, paging and sorting parameters. Spring Boot wires them and HikariCP lends the connections.
A useful check is the import: jakarta.persistence means JPA, org.hibernate means Hibernate, org.springframework.data means Spring Data. In the dependency:tree output, jakarta.persistence-api is JPA, hibernate-core is Hibernate, and spring-data-jpa and HikariCP each come from their own library.
Fixing broken setups from their startup errors
A broken JPA setup fails at startup, which is good: no customer sees it. Examples 2 to 4 are three real failures, each caused by one small mistake.
Example 2 · Broken application.yml: url at the wrong level
Runs in: the jpa-lab Spring Boot project
spring: application: name: jpa-lab main: web-application-type: none datasource: url: ${DB_URL} username: ${DB_USER} password: ${DB_PASSWORD} jpa: hibernate: ddl-auto: validate$ java -jar target/jpa-lab-0.0.1-SNAPSHOT.jar
...
APPLICATION FAILED TO START
***************************
Description:
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.
Reason: Failed to determine a suitable driver classWhat this code does
url,usernameandpasswordhave two spaces, the same asdatasource:, so they arespring.urland so on, andspring.datasourceis empty.- With no URL and no embedded database such as H2 on the classpath, Boot cannot pick a driver and prints this box before Hibernate even starts.
- Fix: indent the three lines by four spaces so they sit under
datasource:.
Example 3 · Broken pom.xml: no MySQL driver
Runs in: a copy of the jpa-lab project without the driver
<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>4.1.1</version> <relativePath/> </parent> <groupId>com.shoplite</groupId> <artifactId>jpa-lab</artifactId> <version>0.0.1-SNAPSHOT</version> <name>jpa-lab</name> <properties> <java.version>17</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build></project>$ java -jar target/jpa-lab-0.0.1-SNAPSHOT.jar
...
2026-10-16T11:21:55.640+05:30 ERROR 22460 --- [jpa-lab] [ main] o.s.boot.SpringApplication : Application run failed
...
Caused by: java.lang.RuntimeException: Failed to load driver class com.mysql.cj.jdbc.Driver
Caused by: java.lang.ClassNotFoundException: com.mysql.cj.jdbc.DriverWhat this code does
- The URL starts with
jdbc:mysql:, so Boot knows the driver class should becom.mysql.cj.jdbc.Driver, but no jar on the classpath contains it. - The last
Caused bysays it plainly:ClassNotFoundException. The code compiled fine, because no class imports the driver. - Fix: add
mysql-connector-jwith<scope>runtime</scope>and rebuild the jar.
Example 4 · Missing environment variable: DB_URL not set
Runs in: the jpa-lab Spring Boot project
spring: datasource: url: ${DB_URL} # DB_URL is not set in this terminal username: ${DB_USER} password: ${DB_PASSWORD}$ java -jar target/jpa-lab-0.0.1-SNAPSHOT.jar
...
2026-10-16T11:18:44.508+05:30 ERROR 9996 --- [jpa-lab] [ main] o.s.boot.SpringApplication : Application run failed
...
Caused by: java.lang.IllegalArgumentException: 'url' must start with "jdbc"What this code does
- With no
DB_URLvariable and no default, Spring keeps the text${DB_URL}as the URL, and HikariCP rejects it: it does not start withjdbc. - Environment variables belong to one terminal window or one run configuration. Opening a new window, or running from the IDE, loses them.
- Fix: set the variable where the app runs, or give a dev default as ShopLite does:
${DB_URL:jdbc:mysql://localhost:3306/shoplite}inapplication-dev.yml.
Read the log in this order: the APPLICATION FAILED TO START box if there is one, then the HHH000247 WARN lines, then the last Caused by line, which is the root cause.
- Box: "'url' attribute is not specified" → no
spring.datasource.urlreached Spring (missing key or YAML indentation). ClassNotFoundException: com.mysql.cj.jdbc.Driver→mysql-connector-jis missing frompom.xml.'url' must start with "jdbc"→ the placeholder was not filled: the environment variable is not set in this terminal.- Communications link failure, Access denied, Unknown database → MySQL, password, database name.
Choosing ddl-auto for dev, test and production
The Section 12 schema (later, Flyway migrations) owns ShopLite's tables everywhere, so validate is right for dev, test and production alike. Example 5 shows the one trap in tests.
Example 5 · validate in tests: an empty test database
Runs in: the shoplite-api Spring Boot project
# src/test/resources/application-test.yml (ShopLite)spring: datasource: url: ${TEST_DB_URL:jdbc:mysql://localhost:3306/shoplite_test} username: ${DB_USER:root} password: ${DB_PASSWORD}# ddl-auto: validate comes from application.yml, as in every profile$ mvn verify # runs the *IT tests too, against an empty shoplite_test database
...
2026-10-16T12:58:35.401+05:30 ERROR 11068 --- [shoplite-api] [ main] j.LocalContainerEntityManagerFactoryBean : Failed to initialize JPA EntityManagerFactory: Unable to build Hibernate SessionFactory [persistence unit: default] ; nested exception is org.hibernate.tool.schema.spi.SchemaManagementException: Schema validation: missing table [categories]
...
[ERROR] Tests run: 3, Failures: 0, Errors: 3, Skipped: 0, Time elapsed: 22.98 s <<< FAILURE! -- in com.shoplite.ApiDocsITWhat this code does
- This happened for real while moving ShopLite to JPA: the new
shoplite_testdatabase had no tables yet. Section 15's tests loaded them with@Sqlper test class, butvalidateruns earlier, when the Spring context starts. - The fix was not to weaken
validate, but to loadreset-test-db.sqlintoshoplite_testonce. After that all 16 tests passed, and each@Sqlreset still works. - The Flyway module removes this one-time step: migrations create the tables before Hibernate validates them.
Per environment:
- dev:
validateagainst your localshoplitedatabase, loaded once fromdb/shoplite-schema.sql. - test:
validateagainstshoplite_test. Load the tables once before the tests;validateruns when the Spring context starts, before any@Sqlscript of a test class (Example 5). - production:
validate, ornoneif a team prefers no check at all; neverupdate,createorcreate-drop.
create-drop has one honest use: throwaway tests on an in-memory database where Hibernate itself builds the tables. ShopLite tests run on MySQL with the real schema, so it does not use it.
Interview drill: ORM vs JDBC, JPA vs Hibernate
Two questions open most JPA interviews. Answer each in three sentences, with one ShopLite example.
ORM vs JDBC: JDBC (or JdbcClient) gives full control and plain SQL, but you write every statement and every row mapping. An ORM maps classes to tables once and writes the SQL, keeps one object per row in a transaction and tracks changes, but hides the SQL and can send too many queries. ShopLite uses JPA for normal CRUD and keeps plain SQL for reports.
JPA vs Hibernate: JPA is the specification in jakarta.persistence; Hibernate is the implementation that Spring Boot 4.1 uses (version 7). Spring Data JPA sits on top and generates repositories. Follow-ups usually ask about ddl-auto, SQL logging and the N+1 problem, all covered in this module.
Module quiz
Questions from the whole module. Your first answer is your score.
Problems
Graded easy to hard, using everything from this module.
Try each one yourself first. Use the hint if you get stuck. Mark it as done when it works.
Exercise 1· Easy
Write JPA, Hibernate, Spring Data JPA, HikariCP or MySQL for each job:
- Lends a connection for each query.
- Defines
@GeneratedValue. - Translates JPQL to MySQL SQL.
- Creates the class behind
CategoryRepository. - Checks the UNIQUE constraint on
categories.name. - Prints
org.hibernate.SQLlog lines.
1. HikariCP 2. JPA 3. Hibernate 4. Spring Data JPA 5. MySQL 6. Hibernate
Exercise 2· Easy
Write a complete pom.xml dependency section for a new Spring Boot 4.1 REST API that uses Spring Data JPA on MySQL and Bean Validation. No versions.
Runs in: a Spring Boot 4.1 Maven project
webmvc, validation and data-jpa starters (no versions) + mysql-connector-j with runtime scope
Exercise 3· Medium
Write application.yml and application-dev.yml from memory for an app that reads MySQL settings from DB_URL, DB_USER, DB_PASSWORD, uses dev as the default profile, validates the schema, and logs formatted SQL with bound values only in dev. In dev, DB_URL and DB_USER have local defaults.
Runs in: a Spring Boot 4.1 project with the ShopLite database
Base: datasource placeholders, profiles.default dev, ddl-auto validate. Dev: url/username defaults, format_sql, org.hibernate.SQL DEBUG, org.hibernate.orm.jdbc.bind TRACE.
Exercise 4· Medium
For each startup log, name the cause and the fix:
Caused by: java.net.ConnectException: Connection refused: getsockoptAccess denied for user 'shoplite_app'@'localhost' (using password: NO)Unknown database 'shoplite_db'Schema validation: missing table [categories]
1. MySQL not running / wrong host or port → start MySQL, fix DB_URL 2. Empty password → set DB_PASSWORD 3. Wrong database name → fix DB_URL or create it 4. Tables not loaded → run db/shoplite-schema.sql
Exercise 5· Medium
Choose ddl-auto for each case and give a one-line reason:
- ShopLite on your laptop.
- ShopLite integration tests on
shoplite_test. - ShopLite on the college placement-cell demo server.
- A one-file experiment on an empty scratch database that you delete afterwards.
1. validate 2. validate 3. validate 4. create (or create-drop)
Exercise 6· Hard
Fix the three mistakes in this setup so the app starts against shoplite with schema validation.
Runs in: a Spring Boot 4.1 project with the ShopLite database
<!-- pom.xml --><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> <version>3.2.0</version></dependency># application.ymlspring: datasource: url: jdbc:mysql://localhost:3306/shoplite username: shoplite_app password: Shop@2026 jpa: hibernate: ddl-auto: update1. Remove <version> (Boot 4.1 manages it) and add mysql-connector-j (runtime).
2. password from ${DB_PASSWORD}, not written in the file.
3. ddl-auto: validate instead of update.Exercise 7· Hard
Interview drill. Answer both questions in exactly three sentences each, with one ShopLite example:
- What is the difference between an ORM and JDBC?
- What is the difference between JPA and Hibernate?
Two answers of three sentences, each naming a ShopLite example.
Exercise 8· Hard
A classmate wants formatted SQL in the log, but the app prints no SQL at all. After fixing that, the SQL is still on one line. Find both mistakes and fix them.
Runs in: the jpa-lab Spring Boot project with the ShopLite database
spring: jpa: properties: format_sql: truelogging: level: org.hibernate.sql: DEBUG1. Logger names are case-sensitive: org.hibernate.SQL, not org.hibernate.sql. 2. Hibernate's setting is hibernate.format_sql: spring.jpa.properties.hibernate.format_sql.
Interview questions
Questions interviewers ask on this topic.
Finish up
Mark complete & continue
Next: ShopLite: add Spring Data JPA and serve categories