Skip to lesson

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

Terminal
mvn dependency:tree
Sample output
$ 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

  • HikariCP arrives through the JDBC starter: the pool, not part of JPA.
  • jakarta.persistence-api is JPA (interfaces and annotations only), hibernate-core is the provider, and spring-orm connects Spring to it.
  • spring-data-jpa is the repository layer; mysql-connector-j is 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

YAML
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
Sample output
$ 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 class

What this code does

  • url, username and password have two spaces, the same as datasource:, so they are spring.url and so on, and spring.datasource is 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
<?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>
Sample output
$ 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.Driver

What this code does

  • The URL starts with jdbc:mysql:, so Boot knows the driver class should be com.mysql.cj.jdbc.Driver, but no jar on the classpath contains it.
  • The last Caused by says it plainly: ClassNotFoundException. The code compiled fine, because no class imports the driver.
  • Fix: add mysql-connector-j with <scope>runtime</scope> and rebuild the jar.

Example 4 · Missing environment variable: DB_URL not set

Runs in: the jpa-lab Spring Boot project

YAML
spring:  datasource:    url: ${DB_URL}           # DB_URL is not set in this terminal    username: ${DB_USER}    password: ${DB_PASSWORD}
Sample output
$ 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_URL variable and no default, Spring keeps the text ${DB_URL} as the URL, and HikariCP rejects it: it does not start with jdbc.
  • 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} in application-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.url reached Spring (missing key or YAML indentation).
  • ClassNotFoundException: com.mysql.cj.jdbc.Driver → mysql-connector-j is missing from pom.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

YAML
# 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
Sample output
$ 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.ApiDocsIT

What this code does

  • This happened for real while moving ShopLite to JPA: the new shoplite_test database had no tables yet. Section 15's tests loaded them with @Sql per test class, but validate runs earlier, when the Spring context starts.
  • The fix was not to weaken validate, but to load reset-test-db.sql into shoplite_test once. After that all 16 tests passed, and each @Sql reset still works.
  • The Flyway module removes this one-time step: migrations create the tables before Hibernate validates them.

Per environment:

  • dev: validate against your local shoplite database, loaded once from db/shoplite-schema.sql.
  • test: validate against shoplite_test. Load the tables once before the tests; validate runs when the Spring context starts, before any @Sql script of a test class (Example 5).
  • production: validate, or none if a team prefers no check at all; never update, create or create-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:

  1. Lends a connection for each query.
  2. Defines @GeneratedValue.
  3. Translates JPQL to MySQL SQL.
  4. Creates the class behind CategoryRepository.
  5. Checks the UNIQUE constraint on categories.name.
  6. Prints org.hibernate.SQL log lines.
Expected output
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

Expected output
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

Expected output
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:

  1. Caused by: java.net.ConnectException: Connection refused: getsockopt
  2. Access denied for user 'shoplite_app'@'localhost' (using password: NO)
  3. Unknown database 'shoplite_db'
  4. Schema validation: missing table [categories]
Expected output
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:

  1. ShopLite on your laptop.
  2. ShopLite integration tests on shoplite_test.
  3. ShopLite on the college placement-cell demo server.
  4. A one-file experiment on an empty scratch database that you delete afterwards.
Expected output
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

Text
<!-- 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: update
Expected output
1. 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:

  1. What is the difference between an ORM and JDBC?
  2. What is the difference between JPA and Hibernate?
Expected output
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

YAML
spring:  jpa:    properties:      format_sql: truelogging:  level:    org.hibernate.sql: DEBUG
Expected output
1. 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