Adding the JPA starter and configuring MySQL
45 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite's API must read its categories from MySQL through JPA. That takes two dependencies, three connection settings and one decision: may Hibernate change your tables, or only check them?
spring-boot-starter-data-jpa and mysql-connector-j
spring-boot-starter-data-jpa is the one dependency that adds JPA to a Spring Boot app. It pulls in Spring Data JPA, Hibernate 7, the Jakarta Persistence API, Spring's JDBC support and the HikariCP connection pool.
Example 1 shows the two dependencies ShopLite adds, with no versions: the Spring Boot parent picks versions that were tested together.
Example 1 · pom.xml: the JPA starter and the MySQL driver
Runs in: the jpa-lab Spring Boot project
<?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> <!-- JPA + Hibernate + Spring Data JPA + JDBC + HikariCP --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <!-- The MySQL JDBC driver, only needed while the app runs --> <dependency> <groupId>com.mysql</groupId> <artifactId>mysql-connector-j</artifactId> <scope>runtime</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build></project>$ mvn dependency:tree
...
[INFO] com.shoplite:jpa-lab:jar:0.0.1-SNAPSHOT
[INFO] +- org.springframework.boot:spring-boot-starter-data-jpa:jar:4.1.1:compile
...
[INFO] | +- org.springframework.boot:spring-boot-starter-jdbc:jar:4.1.1:compile
[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
...
[INFO] BUILD SUCCESSWhat this code does
- Two dependencies and no versions: the
spring-boot-starter-parent4.1.1 decides them all. dependency:treeshows what the starter brought: HikariCP 7.0.2 through the JDBC starter,jakarta.persistence-api3.2.0,hibernate-core7.4.5.Final,spring-ormandspring-data-jpa4.1.1.mysql-connector-j9.7.0 isruntime: on the classpath when the app runs, invisible to the compiler.
mysql-connector-j is MySQL's JDBC driver, with runtime scope because your code never imports its classes. Boot 4.1.1 manages Hibernate 7.4.5, HikariCP 7.0.2 and mysql-connector-j 9.7.0. Section 13 pinned the driver to 26.7.0 by hand because there was no Boot; here the parent's choice wins unless you override it on purpose.
The starter already contains spring-boot-starter-jdbc, so an app moving from JdbcClient replaces that starter with this one and keeps every JdbcClient bean working. Without the driver, startup fails with Failed to load driver class com.mysql.cj.jdbc.Driver and, at the bottom, ClassNotFoundException: com.mysql.cj.jdbc.Driver.
spring.datasource from environment variables
spring.datasource.url, username and password are the three properties that tell Spring Boot how to reach MySQL. From them Boot builds a HikariCP connection pool, the default DataSource.
Example 2 writes the three settings as ${DB_URL}, ${DB_USER} and ${DB_PASSWORD}, so the real values come from environment variables and no password is committed to Git.
Example 2 · src/main/resources/application.yml: MySQL from environment variables
Runs in: the jpa-lab Spring Boot project with the ShopLite database
spring: application: name: jpa-lab main: web-application-type: none # no web server needed for this lab datasource: url: ${DB_URL} username: ${DB_USER} password: ${DB_PASSWORD} jpa: hibernate: ddl-auto: validate # check the entities against the tables, change nothing$ java -jar target/jpa-lab-0.0.1-SNAPSHOT.jar
...
2026-10-16T11:07:29.995+05:30 INFO 23832 --- [jpa-lab] [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2026-10-16T11:07:31.471+05:30 INFO 23832 --- [jpa-lab] [ main] com.zaxxer.hikari.pool.HikariPool : HikariPool-1 - Added connection com.mysql.cj.jdbc.ConnectionImpl@6ad6ae45
2026-10-16T11:07:31.475+05:30 INFO 23832 --- [jpa-lab] [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2026-10-16T11:07:31.743+05:30 INFO 23832 --- [jpa-lab] [ main] org.hibernate.orm.connections.pooling : HHH10001005: Database info:
Database JDBC URL [jdbc:mysql://localhost:3306/shoplite]
Database driver: MySQL Connector/J
Database dialect: MySQLDialect
...What this code does
${DB_URL},${DB_USER}and${DB_PASSWORD}are read from environment variables at startup; the file holds no secret and can be committed.- HikariCP opens its first connection (
Added connection), then Hibernate printsDatabase info: the URL it uses, the MySQL driver and the dialect it picked from the server version. web-application-type: noneis only for this lab, which has no controllers. ShopLite keeps its web server.
Set the three variables before you start the app, the way your terminal does it ($env:DB_URL = "jdbc:mysql://localhost:3306/shoplite" in PowerShell, export DB_URL=jdbc:mysql://localhost:3306/shoplite in zsh) or in the IDE's run configuration, then do the same for DB_USER and DB_PASSWORD. The log lines HikariPool-1 - Start completed and Database info in Example 2 prove the app reached MySQL.
A first entity and repository
An entity is a class marked @Entity whose objects are the rows of one table. Hibernate loads rows into entity objects and saves changed objects back.
Example 3 maps the categories table with one entity and one repository interface, and prints every row at startup.
Example 3 · Category, CategoryRepository and a runner that prints findAll()
Runs in: the jpa-lab Spring Boot project with the ShopLite database
// src/main/java/com/shoplite/lab/category/Category.javapackage com.shoplite.lab.category;
import jakarta.persistence.Column;import jakarta.persistence.Entity;import jakarta.persistence.GeneratedValue;import jakarta.persistence.GenerationType;import jakarta.persistence.Id;import jakarta.persistence.Table;
/** One row of the categories table. */@Entity@Table(name = "categories")public class Category {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "category_id") private Integer id;
private String name;
private Integer parentId;
protected Category() { }
public Integer getId() { return id; }
public String getName() { return name; }
public Integer getParentId() { return parentId; }}
// src/main/java/com/shoplite/lab/category/CategoryRepository.javapackage com.shoplite.lab.category;
import org.springframework.data.jpa.repository.JpaRepository;
public interface CategoryRepository extends JpaRepository<Category, Integer> {}
// src/main/java/com/shoplite/lab/category/CategoryPrinter.javapackage com.shoplite.lab.category;
import org.springframework.boot.CommandLineRunner;import org.springframework.stereotype.Component;
/** Prints every category once, right after the app starts. */@Componentclass CategoryPrinter implements CommandLineRunner {
private final CategoryRepository categories;
CategoryPrinter(CategoryRepository categories) { this.categories = categories; }
@Override public void run(String... args) { System.out.println("Categories in the database: " + categories.count()); for (Category c : categories.findAll()) { System.out.printf("%d %-15s parent=%s%n", c.getId(), c.getName(), c.getParentId()); } }}$ java -jar target/jpa-lab-0.0.1-SNAPSHOT.jar
...
2026-10-16T11:07:34.163+05:30 INFO 23832 --- [jpa-lab] [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2026-10-16T11:07:35.478+05:30 INFO 23832 --- [jpa-lab] [ main] com.shoplite.lab.JpaLabApplication : Started JpaLabApplication in 12.153 seconds (process running for 13.666)
Categories in the database: 7
1 Electronics parent=null
2 Mobiles parent=1
3 Laptops parent=1
4 Accessories parent=1
5 Books parent=null
6 Fashion parent=null
7 Home & Kitchen parent=nullWhat this code does
- The entity maps three columns;
category_idneeds@Columnbecause the field is calledid. Theprotectedconstructor is for Hibernate only. CategoryRepositorydeclares nothing, yet the runner callscount()andfindAll(). Boot started theEntityManagerFactoryand created the repository before the runner ran.- The seven rows come straight from the Section 12 seed data, with
parent=nullfor top-level categories.
The smallest useful entity needs @Entity, @Table(name = "categories"), an @Id field and a no-argument constructor (it may be protected) that Hibernate uses to create objects. The repository extends JpaRepository<Category, Integer>: the entity type and its id type. Boot finds both in the main class's package and below; a class outside it gives "Not a managed type".
Two details matter for the Section 12 schema. The id column is category_id, so the field needs @Column(name = "category_id"); and it is an INT, so the Java type is Integer, not Long. Other fields follow Spring Boot's naming rule (parentId maps to parent_id), and @GeneratedValue(strategy = GenerationType.IDENTITY) leaves new ids to MySQL's AUTO_INCREMENT. The Entities module covers every mapping option.
ddl-auto: who owns the tables
spring.jpa.hibernate.ddl-auto tells Hibernate what to do with the tables at startup: none, validate, update, create or create-drop.
ShopLite lets the Section 12 schema own its tables. Examples 4 and 5 show what create and validate do to them.
Example 4 · ddl-auto=create on an empty scratch database
Runs in: the jpa-lab Spring Boot project with an empty scratch database
java -jar target/jpa-lab-0.0.1-SNAPSHOT.jar --spring.jpa.hibernate.ddl-auto=create --logging.level.org.hibernate.SQL=DEBUG$ java -jar target/jpa-lab-0.0.1-SNAPSHOT.jar --spring.jpa.hibernate.ddl-auto=create --logging.level.org.hibernate.SQL=DEBUG
...
2026-10-16T11:23:09.674+05:30 DEBUG 7308 --- [jpa-lab] [ main] org.hibernate.SQL : drop table if exists categories
2026-10-16T11:23:10.796+05:30 DEBUG 7308 --- [jpa-lab] [ main] org.hibernate.SQL : create table categories (category_id integer not null auto_increment, parent_id integer, name varchar(255), primary key (category_id)) engine=InnoDB
...
Categories in the database: 0What this code does
- With
create, Hibernate first runsdrop table if exists categories. Pointed at your realshoplitedatabase, that line throws your data away at every start. - The table it creates comes only from the entity:
name varchar(255)instead ofVARCHAR(50) NOT NULL, no UNIQUE name, no foreign key to the parent. Section 12's rules are gone. - This ran against an empty database called
shoplite_scratch, so the table is new and empty:Categories in the database: 0. Usecreateonly for throwaway experiments like this one.
Example 5 · ddl-auto=validate catching a Long id on an INT column
Runs in: the jpa-lab Spring Boot project with the ShopLite database
// src/main/java/com/shoplite/lab/category/Category.java (first version)@Id@GeneratedValue(strategy = GenerationType.IDENTITY)@Column(name = "category_id")private Long id; // the column is INT
private String name;
private Long parentId; // column parent_id$ java -jar target/jpa-lab-0.0.1-SNAPSHOT.jar
...
2026-10-16T11:01:18.547+05:30 ERROR 12084 --- [jpa-lab] [ 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: wrong column type encountered in column [category_id] in table [categories]; found [int (Types#INTEGER)], but expecting [bigint (Types#BIGINT)]
...
Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Schema validation: wrong column type encountered in column [category_id] in table [categories]; found [int (Types#INTEGER)], but expecting [bigint (Types#BIGINT)]What this code does
validatecompares each mapped column with the real one: aLongfield expectsbigint, and MySQL hasint. Startup stops before any request is served.- The fix is the Java type:
private Integer id;andprivate Integer parentId;matchINT. Changing the table to fit the entity would be the wrong way round, since the schema owns the tables. - Without
validatethis app would start and work, and the mismatch would surface later in a harder way. A failed start is the cheapest time to find it.
DDL is the part of SQL that creates and changes tables (CREATE, ALTER, DROP). The ddl-auto values:
none: do nothing.validate: compare every entity with its table and stop the app on any difference; change nothing.update: add missing tables and columns, but never drop or fix wrong ones.create: drop the entity tables and create them again at every start.create-drop: like create, and drop them again at shutdown.
ShopLite uses validate. The tables come from the Section 12 schema, with its UNIQUE constraints, foreign keys and CHECKs, so the schema owns the tables and Hibernate only checks them. Spring Boot's own default is none for MySQL (it uses create-drop only for embedded test databases such as H2), so set validate yourself. The Flyway module later turns the schema into migrations and keeps validate.
Predict the output
What does ddl-auto do at startup?
Pick what happens when the app starts.
Round 1 of 2
The real shoplite database holds 7 categories.
Startup errors decoded
A wrong datasource stops the app at startup with a long log. Example 6 shows a full Access denied startup, cut to the lines that matter.
Example 6 · A failed startup: Access denied for user
Runs in: the jpa-lab Spring Boot project with the ShopLite database
# PowerShell: a wrong password on purpose$env:DB_USER = "shoplite_app"$env:DB_PASSWORD = "wrong-password"java -jar target/jpa-lab-0.0.1-SNAPSHOT.jar$ java -jar target/jpa-lab-0.0.1-SNAPSHOT.jar
...
2026-10-16T11:18:16.397+05:30 INFO 26120 --- [jpa-lab] [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2026-10-16T11:18:19.811+05:30 WARN 26120 --- [jpa-lab] [ main] org.hibernate.orm.jdbc.error : HHH000247: ErrorCode: 1045, SQLState: 28000
2026-10-16T11:18:19.812+05:30 WARN 26120 --- [jpa-lab] [ main] org.hibernate.orm.jdbc.error : Access denied for user 'shoplite_app'@'localhost' (using password: YES)
2026-10-16T11:18:19.817+05:30 WARN 26120 --- [jpa-lab] [ main] org.hibernate.orm.jdbc : HHH100046: Could not obtain connection to query JDBC database metadata
...
2026-10-16T11:18:19.977+05:30 ERROR 26120 --- [jpa-lab] [ main] o.s.boot.SpringApplication : Application run failed
...
Caused by: org.hibernate.HibernateException: Unable to determine Dialect without JDBC metadata (please set 'jakarta.persistence.jdbc.url' for common cases or 'hibernate.dialect' when a custom Dialect implementation must be provided)What this code does
- The useful lines come first:
ErrorCode: 1045andAccess denied for user 'shoplite_app'@'localhost' (using password: YES). MySQL received a password and rejected it. - The last
Caused byonly says Hibernate could not read the database's details. It looks like a dialect problem, but the cause is the login above it. - Fix: check
DB_USERandDB_PASSWORDin this terminal (they are per terminal window), or log in with the same values using themysqlcommand to test them.
The real reason is near the top, in Hibernate's HHH000247 WARN lines, or in the last Caused by line; the final "Unable to determine Dialect without JDBC metadata" only means Hibernate could not reach the database. The four common errors:
Communications link failure(Connection refused): MySQL is not running, or the host or port inDB_URLis wrong.Access denied for user 'shoplite_app'@'localhost' (using password: YES): wrong user or password (using password: NOmeansDB_PASSWORDwas empty).Unknown database 'shoplite_db': the database name in the URL does not exist; create it or fix the name.Failed to determine a suitable driver classwith "'url' attribute is not specified": Spring found nospring.datasource.urlat all, often a YAML indentation mistake. An unsetDB_URLgives'url' must start with "jdbc"instead, because the text${DB_URL}is left as it is.
Fix the error
Fix the datasource URL
Read the real error, then pick the line that fixes it.
Round 1 of 2
The app stops at startup. The database name in the URL is wrong.
Error
Caused by: java.sql.SQLSyntaxErrorException: Unknown database 'shoplite_db'
Next step
Check your understanding
12 quick questions