Sub topic 2
Setting up Spring Data JPA in a Spring Boot project
This chapter assumes you can build a basic Spring Boot application with Maven or Gradle and know what a bean and an application.properties file are. It also assumes you know what a JDBC URL is. By the end you will have a working setup that connects to a database, scans for entities and repositories, and logs the SQL it runs.
What you need on the classpath
Spring Boot sets up JPA through auto-configuration. Auto-configuration is a set of conditional configuration classes that activate when certain libraries are on the classpath. You do not write the wiring yourself. You add a starter, a JDBC driver, and properties.
spring-boot-starter-data-jpa brings in:
- Spring Data JPA, which generates repository implementations.
- Hibernate, the JPA provider that turns entity operations into SQL.
- Jakarta Persistence API, which holds the
jakarta.persistenceannotations such as@Entity. - Spring JDBC, Spring transaction support, and the HikariCP connection pool.
You also need a driver for your database. This Maven example uses PostgreSQL:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>The versions come from the Spring Boot parent or BOM, so you do not set them. The H2 dependency, an in-memory database, is limited to the test scope. Chapter 17 uses it for @DataJpaTest.
The code in this tutorial uses the jakarta.persistence package. That means Spring Boot 3 or later and Java 17 or later. Boot 2 projects use javax.persistence instead, and the two packages cannot be mixed.
What happens at startup
The application starts, and Boot's auto-configuration builds the pieces in a fixed order.
Each box is a bean you can inject or override:
- The
DataSourceis a pooled connection source built from thespring.datasource.*properties. - The
EntityManagerFactoryis Hibernate's central object. It reads your entity metadata, picks a dialect, and creates theEntityManagerinstances that hold the persistence context. - The
JpaTransactionManageris what@Transactionaluses. - The repository beans are proxies that Spring Data creates for each repository interface it finds.
Boot detects the Hibernate dialect, the SQL flavor for your database, from the JDBC connection. In Hibernate 6 you almost never set hibernate.dialect yourself.
Configuring the connection
Put this in src/main/resources/application.properties:
spring.datasource.url=jdbc:postgresql://localhost:5432/library
spring.datasource.username=library
spring.datasource.password=${DB_PASSWORD}
spring.jpa.hibernate.ddl-auto=validate
spring.jpa.open-in-view=false
spring.jpa.properties.hibernate.format_sql=true
logging.level.org.hibernate.SQL=debug
logging.level.org.hibernate.orm.jdbc.bind=traceThe ${DB_PASSWORD} placeholder reads an environment variable, so the password never goes into source control.
| Property | Purpose |
|---|---|
| `spring.datasource.url` | JDBC URL. The driver class is inferred from it. |
| `spring.jpa.hibernate.ddl-auto` | What Hibernate does with the schema at startup. |
| `spring.jpa.open-in-view` | Whether the persistence context stays open during web view rendering. |
| `spring.jpa.properties.hibernate.format_sql` | Passes a native Hibernate setting through. Pretty-prints SQL. |
| `logging.level.org.hibernate.SQL` | Logs each SQL statement through the logging system. |
| `logging.level.org.hibernate.orm.jdbc.bind` | Logs bound parameter values (Hibernate 6 logger name). |
Prefer the two logging properties over spring.jpa.show-sql=true. The show-sql flag writes to standard output and bypasses your log configuration.
Choosing a ddl-auto value
spring.jpa.hibernate.ddl-auto controls whether Hibernate changes the schema.
| Value | Behavior | Typical use |
|---|---|---|
| `none` | Does nothing. | Production with a migration tool |
| `validate` | Checks that tables and columns match the entities, and fails at startup if not. | Production, staging |
| `update` | Adds missing tables and columns. Never drops or fixes anything. | Quick prototypes only |
| `create` | Drops and recreates the schema on each start. | Throwaway experiments |
| `create-drop` | Like `create`, and drops the schema on shutdown. | Embedded test databases |
If you do nothing and an embedded database such as H2 is on the classpath, Boot defaults ddl-auto to create-drop. For any other database the default is none. This difference surprises people who move from an H2 prototype to PostgreSQL and find that no tables exist.
Entity and repository discovery
Boot scans for @Entity classes and repository interfaces starting at the package of your @SpringBootApplication class, including its subpackages. A layout like this works with no extra configuration:
com.example.library
├── LibraryApplication.java
├── catalog
│ ├── Author.java
│ ├── Book.java
│ └── BookRepository.javaA minimal main class with a startup check looks like this:
package com.example.library;
import com.example.library.catalog.BookRepository;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class LibraryApplication {
public static void main(String[] args) {
SpringApplication.run(LibraryApplication.class, args);
}
@Bean
ApplicationRunner countBooks(BookRepository books) {
return args -> System.out.println("Books in database: " + books.count());
}
}The runner calls count(), a method inherited from the repository interface. If this prints a number, the connection, the entity mapping, and the repository proxy all work.
You do not need @EnableJpaRepositories or @EntityScan in a standard layout. Add them only when entities or repositories live outside the main class's package tree, for example in a shared module:
package com.example.library;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@SpringBootApplication
@EntityScan("com.example.shared.model")
@EnableJpaRepositories("com.example.shared.data")
public class LibraryApplication {
}Open session in view
Boot enables spring.jpa.open-in-view by default in web applications. It keeps the EntityManager open for the whole HTTP request, so lazy associations can load while a controller or view serializes the response. Boot logs a warning at startup about this.
The cost is that database queries can run anywhere in the request, including in JSON serialization, and a connection may be held longer than needed. Setting it to false forces you to load what you need inside the service layer. Chapter 13 covers lazy loading errors that this setting exposes.
Common setup errors
| Symptom | Likely cause and fix |
|---|---|
| `Failed to determine a suitable driver class` | No `spring.datasource.url`, or no driver on the classpath. Add both. |
| `Not a managed type: class ...` | The entity is outside the scanned packages. Move it or add `@EntityScan`. |
| `No qualifying bean of type ...Repository` | The repository is outside the scanned packages, or `@EnableJpaRepositories` limits the scan. |
| `Schema-validation: missing table [books]` | `ddl-auto=validate` and the table does not exist. Create it through a migration. |
| `ClassNotFoundException: javax.persistence...` | A Boot 2 library on Boot 3. Use the Jakarta versions. |
| `Connection refused` at startup | The database is not running or the URL host or port is wrong. |
Checking the setup
Start the application with the logging properties above. You should see Hikari report a started pool, Hibernate report the dialect it detected, and the runner's count line. Set logging.level.org.hibernate.SQL=debug before you write queries, so you can see every statement your repositories produce from the start.
Exercise
You move a prototype from H2 to PostgreSQL. The app starts, but every query fails with "relation does not exist", although it worked on H2 without any schema scripts. What caused the difference, and what are two reasonable fixes?
Show answer
With an embedded database such as H2 on the classpath, Boot defaults ddl-auto to create-drop, so Hibernate built the tables from the entities. For PostgreSQL the default is none, so no tables were created. Fixes: add a migration tool such as Flyway with a script that creates the tables and set ddl-auto to validate, or (for a throwaway environment only) set ddl-auto to create or update explicitly.
Exercise
Your entities live in the package com.example.shared.model, but your main class is in com.example.library. Startup fails with "Not a managed type". What do you add, and what side effect should you check for?
Show answer
Add @EntityScan("com.example.shared.model") to the main class. The side effect is that @EntityScan replaces the default scan, so any entities in com.example.library and its subpackages are no longer found unless you list that package too, for example @EntityScan({"com.example.library", "com.example.shared.model"}).