In Part 1, we understood how Spring manages objects using annotations like @Component, @Service, and @Repository.
But we haven't answered one important question yet.
How does our Spring Boot application actually communicate with a database?
Suppose Asha is building a library management application. She wants to store books, retrieve them, update their information, and delete them.
Java objects live in application memory, but books need to be stored in a database so they remain available even after the application restarts.
How do we connect these two worlds?
This is where JDBC comes in.
When I first encountered JDBC, I was confused by terms like Connection, Statement, PreparedStatement, ResultSet, and DataSource.
Then Spring introduced something called JdbcTemplate. It looked much simpler, but I wanted to understand what it was actually doing behind the scenes.
In this post, we'll understand the complete journey, starting from basic JDBC and moving towards Spring Boot's database integration.
We'll also learn how schema.sql and data.sql automatically create tables and insert records when our application starts.
Versions used in this post:
- Java 17
- Spring Boot 4.2.0
- Spring Framework 7.1.0
- H2 Database for examples
The examples use Java 17-compatible code.
Table of contents
- Before we write database code
- Understanding JDBC
- Why Spring provides JdbcTemplate
- Initialize the database with schema.sql
- Insert starter data with data.sql
- Put everything together
- What else should you know?
- Which one should I use?
- Common mistakes
- Quick recap
- Try it yourself
Before we write database code
Before writing any Java code, let's prepare our Spring Boot project.
We'll use an H2 database for our examples.
Why H2?
H2 is a lightweight relational database written in Java. It supports in-memory databases, which makes it convenient for learning and testing without installing a separate database server.
You can later replace H2 with PostgreSQL, MySQL, or another relational database.
Add JDBC dependencies
First, we need to tell Spring Boot that our application will communicate with a relational database using JDBC.
For this, we need two dependencies:
spring-boot-starter-jdbch2
Add the following dependencies to your pom.xml:
<dependencies>
<!-- Spring JDBC support -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- H2 Database -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
Notice that we haven't specified versions for these dependencies.
Why?
Our pom.xml should use the Spring Boot 4.2.0 parent or its dependency management BOM. Spring Boot manages compatible dependency versions for us.
What does each dependency provide?
spring-boot-starter-jdbc provides Spring's JDBC support and the required database connection infrastructure.
It also includes HikariCP, a database connection pool.
h2 provides the actual database and its JDBC driver.
A JDBC driver is a library that allows Java applications to communicate with a particular database.
For example:
- H2 uses the H2 JDBC driver.
- PostgreSQL uses the PostgreSQL JDBC driver.
- MySQL uses the MySQL JDBC driver.
Behind the scenes
Spring Boot Application
|
v
spring-boot-starter-jdbc
|
+---------+---------+
| |
v v
Spring JDBC HikariCP
| |
+---------+---------+
|
v
JDBC Driver
|
v
H2 Database
Once Maven downloads these dependencies, we can start writing database-related code.
Configure the database connection
Now we need to tell our application where the database is located.
Create the following file:
src/main/resources/application.properties
Add these properties:
spring.datasource.url=jdbc:h2:mem:librarydb;DB_CLOSE_DELAY=-1
spring.datasource.username=sa
spring.datasource.password=
spring.sql.init.mode=always
Let's understand each property.
1. spring.datasource.url
spring.datasource.url=jdbc:h2:mem:librarydb;DB_CLOSE_DELAY=-1
This tells Spring Boot which database to connect to.
Let's break the URL into pieces:
jdbc:h2:mem:librarydb
| | |
| | +-- Database name
| |
| +------ In-memory database
|
+--------- JDBC protocol and H2 driver
mem means that the database is stored in memory rather than in a persistent database file.
DB_CLOSE_DELAY=-1 keeps the in-memory database alive until the JVM process exits, even when individual connections are closed.
2. spring.datasource.username
spring.datasource.username=sa
This specifies the database username.
3. spring.datasource.password
spring.datasource.password=
Our local H2 example uses an empty password.
Never copy this configuration into a production environment without properly securing your database credentials.
4. spring.sql.init.mode
spring.sql.init.mode=always
We'll understand this property in detail when we discuss schema.sql and data.sql.
For now, remember that it tells Spring Boot to execute SQL initialization scripts even when the database is not an embedded database.
Behind the scenes
Spring Boot sees the database configuration and automatically creates a DataSource bean.
A DataSource is an object responsible for providing database connections.
With the JDBC starter, Spring Boot generally uses HikariCP as the connection pool.
A connection pool maintains reusable database connections instead of creating a completely new database connection for every operation.
Spring Boot Application
|
v
DataSource
|
v
HikariCP
|
+---------+---------+
| | |
v v v
Connection Connection Connection
1 2 3
| | |
+---------+---------+
|
v
H2 Database
This is why we don't need to manually create a database connection every time we want to execute a query.
Spring Boot handles the infrastructure for us.
Understanding JDBC
JDBC stands for Java Database Connectivity.
It is a standard Java API that allows Java applications to communicate with relational databases.
Think about a situation where you want to talk to someone who speaks a different language.
You need something that helps both sides communicate.
JDBC plays a similar role between Java applications and databases.
Java provides a common API, and database vendors provide JDBC drivers that implement the communication with their respective databases.
For example, the same Java JDBC API can communicate with PostgreSQL or MySQL, provided the appropriate driver and connection configuration are available.
The JDBC building blocks
Before writing code, let's understand the important JDBC classes and interfaces.
1. DriverManager
DriverManager is a JDBC class that can establish database connections using a suitable registered JDBC driver.
We generally use it in simple standalone JDBC programs.
2. Connection
A Connection represents an active connection between our Java application and the database.
We need this connection to execute SQL statements.
3. Statement
A Statement is used to execute SQL statements.
It is suitable for executing SQL that doesn't require input parameters.
4. PreparedStatement
A PreparedStatement represents a precompiled SQL statement that can receive parameter values.
It is preferred for queries that contain user-provided values.
5. ResultSet
A ResultSet contains the rows returned by a SELECT query.
We can iterate through the rows and retrieve column values.
6. DataSource
DataSource is an alternative and generally preferred way to obtain database connections in applications.
It works well with connection pools such as HikariCP.
Let's understand their relationship.
Java Application
|
v
JDBC API
|
+-------+-------+
| |
v v
DriverManager DataSource
| |
| v
| Connection
| |
+-------+-------+
|
v
Connection
|
+-------+-------+
| |
v v
Statement PreparedStatement
|
v
ResultSet
|
v
Java Objects
One important distinction:
DriverManager and DataSource are ways to obtain connections. They are not the same thing as a database connection itself.
A small JDBC program
Let's write a small Java program to understand how JDBC actually works.
We'll create a table, insert a book, and retrieve it.
This is a standalone JDBC example. It doesn't use Spring's JdbcTemplate.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JdbcDemo {
public static void main(String[] args) throws SQLException {
String url = "jdbc:h2:mem:jdbc_demo;DB_CLOSE_DELAY=-1";
// 1. Establish database connection
try (Connection connection =
DriverManager.getConnection(url, "sa", "")) {
// 2. Create a table
try (Statement statement = connection.createStatement()) {
statement.execute("""
CREATE TABLE books (
id BIGINT PRIMARY KEY,
title VARCHAR(100) NOT NULL
)
""");
// 3. Insert a book
statement.executeUpdate(
"INSERT INTO books (id, title) " +
"VALUES (1, 'Effective Java')"
);
}
// 4. Prepare SELECT query
String sql = "SELECT id, title FROM books WHERE id = ?";
try (PreparedStatement ps =
connection.prepareStatement(sql)) {
// 5. Provide parameter value
ps.setLong(1, 1L);
// 6. Execute query
try (ResultSet rs = ps.executeQuery()) {
// 7. Read returned row
if (rs.next()) {
System.out.println(
"Book ID: " + rs.getLong("id")
);
System.out.println(
"Title: " + rs.getString("title")
);
}
}
}
}
}
}
Output:
Book ID: 1
Title: Effective Java
Let's understand what happened.
First, we established a connection using DriverManager.
Then, we created a table using Statement.
After that, we inserted a book into the table.
Finally, we prepared a SELECT query, supplied the ID, executed the query, and read the returned record using ResultSet.
Behind the scenes
The JDBC execution flow looks like this:
Java Application
|
v
DriverManager.getConnection()
|
v
Connection
|
v
PreparedStatement
|
v
SQL Query
|
v
Database Driver
|
v
Database
|
v
Query Result
|
v
ResultSet
|
v
Java Application
Now you might be thinking:
This is quite a lot of code just to fetch one record!
And you're right.
Imagine writing this connection, statement, result-set, and exception-handling code for every database operation in a large application.
It becomes repetitive.
This is exactly the problem Spring's JDBC abstraction solves.
Why Spring provides JdbcTemplate
Spring provides a class called JdbcTemplate to simplify JDBC database operations.
JdbcTemplate is a Spring JDBC class that handles repetitive JDBC operations while allowing us to focus on SQL queries and result processing.
Remember our previous JDBC example?
We manually handled:
- Opening database connections.
- Creating statements.
- Executing SQL.
- Iterating through result sets.
- Closing resources.
- Handling SQL exceptions.
With JdbcTemplate, Spring handles most of these responsibilities.
We still write SQL because Spring doesn't magically understand our business queries.
The difference is that we don't need to manage all the low-level JDBC boilerplate ourselves.
What JdbcTemplate takes care of
Let's compare the responsibilities.
With normal JDBC:
Developer
|
v
Open Connection
|
v
Create Statement
|
v
Execute SQL
|
v
Process ResultSet
|
v
Handle Exceptions
|
v
Close Resources
With JdbcTemplate:
Developer
|
v
Write SQL
|
v
Provide Parameters
|
v
Map Query Results
|
v
JdbcTemplate
|
+------+------+
| |
v v
Execute SQL Manage Resources
| |
v v
Database Handle Exceptions
Notice the difference?
We focus on what query needs to execute and what to do with the returned data.
Spring handles the repetitive JDBC operations.
Let's see how to use it.
First, inject JdbcTemplate using constructor injection:
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
@Repository
public class BookRepository {
private final JdbcTemplate jdbcTemplate;
public BookRepository(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
}
Notice something important.
We didn't create a JdbcTemplate object using new.
We didn't configure a DataSource manually either.
Why?
Because Spring Boot automatically configures both when the required JDBC dependency and database configuration are available.
This is called auto-configuration.
The JdbcTemplate instance is also thread-safe once configured, so a single shared instance can be injected into multiple repositories.
Querying rows with RowMapper
Now suppose we want to fetch all books from the database.
Our database contains:
+----+------------------+------------------+
| id | title | author |
+----+------------------+------------------+
| 1 | Effective Java | Joshua Bloch |
| 2 | Clean Code | Robert C. Martin |
+----+------------------+------------------+
The database returns rows, but our application generally works with Java objects.
We need something that converts database rows into Java objects.
This is where RowMapper comes in.
RowMapper is an interface that maps one row of a ResultSet to one Java object.
For example, consider this Java record:
public record Book(
Long id,
String title,
String author
) {}
Now we can map database rows into Book objects.
List<Book> books = jdbcTemplate.query(
"SELECT id, title, author FROM books",
(rs, rowNum) -> new Book(
rs.getLong("id"),
rs.getString("title"),
rs.getString("author")
)
);
Output:
[
Book[id=1, title=Effective Java, author=Joshua Bloch],
Book[id=2, title=Clean Code, author=Robert C. Martin]
]
Let's understand the arguments passed to query().
jdbcTemplate.query(
"SELECT id, title, author FROM books",
(rs, rowNum) -> new Book(
rs.getLong("id"),
rs.getString("title"),
rs.getString("author")
)
);
The first argument is the SQL query.
The second argument is a RowMapper.
It tells Spring how to convert each returned database row into a Java object.
Inside the lambda:
-
rsrepresents the currentResultSet. -
rowNumrepresents the current row number. -
rs.getLong("id")retrieves the ID column. -
rs.getString("title")retrieves the title column. -
rs.getString("author")retrieves the author column.
Spring automatically calls the mapper for each returned row.
Behind the scenes
Suppose our database returns two rows.
ResultSet
|
+------+------+
| |
v v
Row 1 Row 2
| |
v v
RowMapper RowMapper
| |
v v
Book Object Book Object
| |
+------+------+
|
v
List<Book>
That's the basic idea behind RowMapper.
There is no need to manually iterate through the ResultSet using while (rs.next()) when using this query() approach.
Inserting updating and deleting rows
So far, we have only fetched data.
But a real application also needs to insert, update, and delete records.
For these operations, JdbcTemplate provides the update() method.
Don't get confused by the method name.
The update() method is used for INSERT, UPDATE, and DELETE statements.
Let's see each operation.
1. Insert a book
int rows = jdbcTemplate.update(
"INSERT INTO books (title, author) VALUES (?, ?)",
"Design Patterns",
"Gang of Four"
);
System.out.println("Rows inserted: " + rows);
Output:
Rows inserted: 1
2. Update a book
Suppose we want to update the author of the book with ID 1.
int rows = jdbcTemplate.update(
"UPDATE books SET author = ? WHERE id = ?",
"Joshua Bloch - Updated",
1L
);
System.out.println("Rows updated: " + rows);
Output:
Rows updated: 1
3. Delete a book
Now let's delete the book with ID 2.
int rows = jdbcTemplate.update(
"DELETE FROM books WHERE id = ?",
2L
);
System.out.println("Rows deleted: " + rows);
Output:
Rows deleted: 1
Why does every operation return 1?
Because the update() method returns the number of rows affected by the SQL statement.
If no matching record exists for an UPDATE or DELETE operation, it normally returns 0.
There is also another useful method called queryForObject().
It is commonly used when we expect a single scalar value or one result.
For example:
Integer count = jdbcTemplate.queryForObject(
"SELECT COUNT(*) FROM books",
Integer.class
);
System.out.println("Total books: " + count);
Output:
Total books: 2
Behind the scenes
The methods have different responsibilities:
JdbcTemplate
|
+------------+------------+
| | |
v v v
query() update() queryForObject()
| | |
v v v
SELECT INSERT/ Single value
UPDATE/ or one object
DELETE
A useful rule:
-
query()for retrieving multiple rows. -
queryForObject()for retrieving a single value or object. -
update()for INSERT, UPDATE, and DELETE.
Understanding placeholders and SQL injection
You might have noticed something in our SQL statements:
"SELECT * FROM books WHERE id = ?"
What is that question mark?
It is a parameter placeholder used by a prepared statement.
We can provide its value separately:
jdbcTemplate.query(
"SELECT * FROM books WHERE id = ?",
rowMapper,
1L
);
Here, 1L is supplied as the value for the first placeholder.
Why do we separate the SQL query and its values?
One important reason is security.
Consider this bad example:
String title = userInput;
String sql =
"SELECT * FROM books WHERE title = '" + title + "'";
We are directly joining user input with SQL.
A malicious user could provide input that changes the meaning of the SQL statement.
This is one way SQL injection vulnerabilities occur.
Instead, use parameter placeholders:
String sql = "SELECT * FROM books WHERE title = ?";
List<Book> books = jdbcTemplate.query(
sql,
rowMapper,
title
);
The parameter is bound separately rather than being concatenated into the SQL statement.
This helps prevent SQL injection through parameter values.
Behind the scenes
SQL Template
|
v
SELECT * FROM books
WHERE title = ?
|
v
PreparedStatement
|
v
Bind User Value
|
v
Execute SQL
|
v
Database
One important limitation:
Placeholders are meant for values, not SQL identifiers.
For example, you cannot safely use ? as a table name or column name.
For dynamic sorting or column selection, validate against an explicit allowlist instead of directly inserting user input into SQL.
Initialize the database with schema.sql
Now we know how to communicate with the database.
But there is another problem.
When our application starts for the first time, the database might not contain any tables.
Should we manually create all tables every time?
No.
Spring Boot provides automatic database initialization using SQL scripts.
One of these scripts is called schema.sql.
Create the books table
In SQL, we use a CREATE TABLE statement to define the structure of a table.
This is called DDL.
DDL stands for Data Definition Language.
It is used to define database structures such as tables, columns, and constraints.
Create the following file:
src/main/resources/schema.sql
Add:
CREATE TABLE IF NOT EXISTS books (
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
title VARCHAR(150) NOT NULL,
author VARCHAR(120) NOT NULL
);
Let's understand the statement.
1. CREATE TABLE books
Creates a new table named books.
2. id BIGINT
Defines an ID column that stores large integer values.
3. GENERATED BY DEFAULT AS IDENTITY
Tells the database to generate an ID when we don't provide one.
4. PRIMARY KEY
Makes the ID the primary key.
A primary key uniquely identifies each record in a table.
5. title VARCHAR(150)
Defines a text column with a maximum length of 150 characters.
6. NOT NULL
Means the column cannot contain a NULL value.
Expected database structure
BOOKS TABLE
+--------------------------------+
| books |
+--------------------------------+
| id BIGINT PRIMARY |
| title VARCHAR(150) NOT NULL |
| author VARCHAR(120) NOT NULL |
+--------------------------------+
Now we have defined the structure of our books table.
But who executes this SQL statement?
How Spring Boot finds schema.sql
Here is something interesting.
We never called the schema.sql file from our Java code.
We never wrote:
new File("schema.sql");
So how does it execute?
Spring Boot automatically looks for SQL initialization scripts in the classpath.
By default, it looks for:
optional:classpath*:schema.sql
For our project, the directory structure should look like this:
src
|
+-- main
|
+-- java
| |
| +-- com.example.library
| +-- LibraryApplication.java
|
+-- resources
|
+-- application.properties
+-- schema.sql
Notice that schema.sql is inside the root of the resources directory.
During the build, Maven places these resources on the application's classpath.
Spring Boot discovers the script and executes it during database initialization.
Behind the scenes
Application Startup
|
v
Spring Boot Detects
DataSource
|
v
Database Initialization
|
v
Search for schema.sql
|
v
Execute CREATE TABLE
|
v
Books Table Created
The important point is that schema.sql is not a special Java class.
It is a conventional SQL script that Spring Boot automatically discovers.
You can also configure a custom location using:
spring.sql.init.schema-locations=classpath:database/schema.sql
This tells Spring Boot to look for the script in:
src/main/resources/database/schema.sql
Insert starter data with data.sql
Creating tables is only half the work.
What happens when we start the application and the books table is empty?
For development, learning, and testing, it is often useful to insert some initial records automatically.
This is where data.sql comes in.
data.sql is an SQL script that Spring Boot can execute to insert initial data into the database.
Add sample books
Create another file:
src/main/resources/data.sql
Add:
INSERT INTO books (title, author)
VALUES ('Effective Java', 'Joshua Bloch');
INSERT INTO books (title, author)
VALUES ('Clean Code', 'Robert C. Martin');
INSERT INTO books (title, author)
VALUES ('Design Patterns', 'Gang of Four');
These statements insert three records into the books table.
Notice something.
We didn't specify the id column.
Why?
Because we configured the column to generate its own identity value.
The database automatically assigns IDs.
Expected records
+----+------------------+------------------+
| id | title | author |
+----+------------------+------------------+
| 1 | Effective Java | Joshua Bloch |
| 2 | Clean Code | Robert C. Martin |
| 3 | Design Patterns | Gang of Four |
+----+------------------+------------------+
Behind the scenes
The startup flow now looks like this:
Spring Boot Startup
|
v
DataSource Created
|
v
schema.sql
|
v
CREATE TABLE books
|
v
data.sql
|
v
INSERT Records
|
v
Application Ready
Notice the order.
The table must exist before we insert records into it.
Spring Boot performs its basic script initialization in the appropriate order, with schema initialization before data initialization.
Control when SQL scripts run
Let's understand an important configuration property:
spring.sql.init.mode
It controls when Spring Boot executes SQL initialization scripts.
There are three possible values.
1. embedded
spring.sql.init.mode=embedded
This is the default behaviour.
SQL initialization runs when using an embedded database such as H2.
2. always
spring.sql.init.mode=always
This forces SQL initialization scripts to run regardless of whether the database is embedded or external.
For example, if you are using PostgreSQL and want Spring Boot to execute schema.sql and data.sql, you need this setting.
3. never
spring.sql.init.mode=never
Disables basic SQL script initialization.
You can also customize the script locations:
spring.sql.init.schema-locations=classpath:database/schema.sql
spring.sql.init.data-locations=classpath:database/data.sql
And you can use database-specific scripts.
For example:
src/main/resources
|
+-- schema.sql
+-- data.sql
|
+-- schema-h2.sql
+-- data-h2.sql
|
+-- schema-postgresql.sql
+-- data-postgresql.sql
Configure the platform:
spring.sql.init.platform=postgresql
Spring Boot can then process the corresponding platform-specific scripts.
One more useful setting:
spring.sql.init.continue-on-error=false
By default, initialization fails when a SQL script produces an error.
This is generally useful because an application should not silently start with an incorrectly initialized database.
Important note:
Don't blindly execute data.sql against a persistent production database on every startup.
The INSERT statements can create duplicate records when the application restarts.
For a real application, use a proper database migration strategy or carefully designed idempotent initialization scripts.
We will discuss migration tools shortly.
Put everything together
Now we've learned all the individual concepts.
Let's build a small working example using:
- Spring Boot
- H2 Database
- JdbcTemplate
- schema.sql
- data.sql
- Repository layer
The application will fetch all books and insert a new book.
Book model
First, create a Java record representing our book.
File:
Book.java
package com.example.library.model;
public record Book(
Long id,
String title,
String author
) {}
Why are we using a record?
Java records provide a concise way to represent data.
The compiler automatically generates useful methods such as:
- Constructor
- Accessor methods
equals()hashCode()toString()
We don't need to write all those methods manually.
Notice that this is just a Java record.
We are using JDBC, so we don't need to annotate it with @Entity.
Repository using JdbcTemplate
Now create:
BookRepository.java
package com.example.library.repository;
import com.example.library.model.Book;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
@Repository
public class BookRepository {
private final JdbcTemplate jdbcTemplate;
public BookRepository(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
private final RowMapper<Book> bookRowMapper =
(rs, rowNum) -> new Book(
rs.getLong("id"),
rs.getString("title"),
rs.getString("author")
);
// Fetch all books
public List<Book> findAll() {
String sql = """
SELECT id, title, author
FROM books
ORDER BY id
""";
return jdbcTemplate.query(sql, bookRowMapper);
}
// Fetch a book by ID
public Optional<Book> findById(Long id) {
String sql = """
SELECT id, title, author
FROM books
WHERE id = ?
""";
List<Book> books = jdbcTemplate.query(
sql,
bookRowMapper,
id
);
return books.stream().findFirst();
}
// Insert a new book
public int save(String title, String author) {
String sql = """
INSERT INTO books (title, author)
VALUES (?, ?)
""";
return jdbcTemplate.update(sql, title, author);
}
// Update a book
public int updateAuthor(Long id, String author) {
String sql = """
UPDATE books
SET author = ?
WHERE id = ?
""";
return jdbcTemplate.update(sql, author, id);
}
// Delete a book
public int deleteById(Long id) {
String sql = "DELETE FROM books WHERE id = ?";
return jdbcTemplate.update(sql, id);
}
}
Let's understand what we implemented.
-
findAll()retrieves every book. -
findById()retrieves a book using its ID. -
save()inserts a new book. -
updateAuthor()updates an existing book's author. -
deleteById()deletes a book using its ID.
All database operations use the same injected JdbcTemplate object.
Notice that we used Optional<Book> in findById().
Why?
Because the requested book might not exist.
Instead of returning null, Optional provides a better way to represent the possibility that no matching record was found.
Also notice that we used ORDER BY id in findAll().
SQL does not guarantee row ordering unless we explicitly request it.
Run the application
Now create the main Spring Boot application.
File:
LibraryApplication.java
package com.example.library;
import com.example.library.repository.BookRepository;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class LibraryApplication {
public static void main(String[] args) {
SpringApplication.run(
LibraryApplication.class,
args
);
}
@Bean
CommandLineRunner run(BookRepository repository) {
return args -> {
// Fetch all books
System.out.println(
"All books: " + repository.findAll()
);
// Fetch a book by ID
System.out.println(
"Book with ID 1: " + repository.findById(1L)
);
// Insert a new book
System.out.println(
"Rows inserted: " +
repository.save(
"Head First Java",
"Kathy Sierra"
)
);
// Count books
System.out.println(
"Total books: " + repository.findAll().size()
);
};
}
}
Now run the application.
Expected application output (excluding Spring Boot startup logs):
All books: [
Book[id=1, title=Effective Java, author=Joshua Bloch],
Book[id=2, title=Clean Code, author=Robert C. Martin],
Book[id=3, title=Design Patterns, author=Gang of Four]
]
Book with ID 1: Optional[
Book[id=1, title=Effective Java, author=Joshua Bloch]
]
Rows inserted: 1
Total books: 4
Our application successfully:
- Started Spring Boot.
- Created the database connection.
- Executed
schema.sql. - Executed
data.sql. - Created the
BookRepositorybean. - Injected
JdbcTemplate. - Fetched books from the database.
- Inserted another book.
That's the complete flow!
Notice how we never manually created a database connection inside our repository.
We simply injected JdbcTemplate and focused on writing SQL queries.
What else should you know?
Before moving to Spring Data JPA, there are two more things worth understanding.
JDBC versus JdbcTemplate versus Spring Data JPA
You will encounter these three terms frequently.
Let's understand their relationship.
JDBC
JDBC is the standard Java API for database connectivity.
It provides low-level interfaces such as:
- Connection
- Statement
- PreparedStatement
- ResultSet
You are responsible for writing SQL and handling much of the database interaction.
JdbcTemplate
JdbcTemplate is Spring's JDBC abstraction.
It still uses SQL, but Spring handles repetitive JDBC operations such as resource management and exception translation.
You write SQL and decide how the results should be mapped.
Spring Data JPA
Spring Data JPA provides a higher-level repository abstraction built on top of JPA.
JPA is a specification that defines how Java objects can be mapped to relational database records.
With Spring Data JPA, you can define repository interfaces and let Spring Data generate implementations for common database operations.
For example:
public interface BookRepository
extends JpaRepository<Book, Long> {
}
You don't need to write basic SQL queries for every CRUD operation.
We'll explore this properly in Part 3.
Behind the scenes
Your Application
|
+------+------+
| | |
v v v
JDBC JdbcTemplate Spring Data JPA
| | |
| v v
| Spring JDBC JPA Provider
| | |
+------+------+
|
v
Database
This diagram is conceptual.
Spring Data JPA typically uses a JPA provider such as Hibernate, which handles object-relational mapping and persistence operations.
Also, don't confuse Spring JDBC with Spring Data JDBC. They are separate Spring technologies with different abstractions.
When to use Flyway or Liquibase
So far, we used:
-
schema.sqlto create database tables. -
data.sqlto insert initial records.
This is convenient for small applications and learning.
But imagine a real application with 50 tables.
A few months later, you need to:
- Add a new column.
- Change a column's data type.
- Create an index.
- Add a new table.
- Update existing records.
How will you track all these changes?
This is where database migration tools become useful.
Two popular options are:
Flyway
Flyway manages database changes using versioned SQL migration files.
For example:
src/main/resources/db/migration
|
+-- V1__create_books_table.sql
|
+-- V2__create_users_table.sql
|
+-- V3__add_book_price_column.sql
|
+-- V4__create_orders_table.sql
Flyway tracks which migrations have already been applied.
When you start your application, it applies the pending migrations in the correct order.
Liquibase
Liquibase is another database migration tool.
It supports defining database changes using formats such as:
- XML
- YAML
- JSON
- SQL
It tracks changes using a changeset-based migration system.
Why are these tools useful?
Imagine you work with five developers.
One developer adds a column, another creates an index, and another creates a table.
Without a migration strategy, it becomes difficult to know which database changes have already been applied.
Migration tools help make database changes version-controlled, repeatable, and manageable across environments.
For real applications, prefer one schema management strategy rather than mixing multiple initialization mechanisms.
Which one should I use?
Let's summarize when to choose each approach.
Choose JDBC when:
- You want direct control over SQL.
- You need low-level database access.
- You want to understand how Java communicates with databases.
Choose JdbcTemplate when:
- You want to write SQL without repetitive JDBC boilerplate.
- You need complete control over queries.
- You are implementing custom SQL-based repositories.
Choose Spring Data JPA when:
- Your application works primarily with Java entities.
- You need common CRUD operations.
- You want repository interfaces and ORM support.
- You don't want to manually write SQL for every operation.
Choose schema.sql and data.sql when:
- You are learning Spring Boot.
- You need simple database initialization.
- You are creating a small demonstration or test application.
Choose Flyway or Liquibase when:
- Your application has a database schema that evolves.
- Multiple developers work on the same database.
- You need controlled database migrations across environments.
My recommendation:
Start with JDBC and JdbcTemplate to understand how database operations actually work.
Then move to Spring Data JPA.
Understanding JDBC first will help you appreciate what JPA and Hibernate are doing behind the scenes.
Common mistakes
Let's look at six mistakes beginners frequently make.
1. Confusing JDBC with JdbcTemplate
JDBC is the standard Java database connectivity API, while JdbcTemplate is Spring's abstraction built on top of JDBC.
Understand the difference before choosing an approach.
2. Creating a new database connection for every operation
Manually opening and closing connections repeatedly can introduce unnecessary boilerplate.
Use Spring's configured DataSource and JdbcTemplate in normal Spring applications.
3. Using string concatenation in SQL queries
Building SQL queries by directly joining user input can cause SQL injection vulnerabilities.
Use ? placeholders and pass parameter values separately.
4. Forgetting the correct location of schema.sql and data.sql
Spring Boot searches the classpath for these scripts by default.
Put them inside src/main/resources, unless you configure custom locations.
5. Assuming SQL scripts run against every database automatically
By default, basic SQL script initialization runs for embedded databases.
For an external database, configure:
spring.sql.init.mode=always
6. Mixing database initialization strategies without understanding their order
Using Hibernate schema generation, SQL initialization scripts, and Flyway or Liquibase together without a clear strategy can cause conflicts.
Choose one schema management approach and understand the initialization order before combining tools.
Quick recap
Let's revise everything we learned.
- JDBC stands for Java Database Connectivity.
- JDBC provides a standard API for Java applications to communicate with relational databases.
- A JDBC driver allows Java to communicate with a specific database.
-
Connectionrepresents a database connection. -
PreparedStatementexecutes parameterized SQL statements. -
ResultSetcontains rows returned by a SELECT query. -
DataSourceprovides database connections and can work with connection pools. -
JdbcTemplatesimplifies JDBC database operations. -
query()retrieves multiple records. -
queryForObject()retrieves a single value or object. -
update()executes INSERT, UPDATE, and DELETE statements. -
RowMapperconverts database rows into Java objects. - Parameter placeholders help prevent SQL injection through user-provided values.
-
schema.sqlcreates database structures. -
data.sqlinserts initial database records. - Spring Boot automatically discovers these scripts from the classpath.
-
spring.sql.init.modecontrols when SQL initialization happens. - Flyway and Liquibase help manage database schema changes over time.
- Spring Data JPA provides a higher-level repository abstraction that we'll learn in Part 3.
Try it yourself
Practice idea:
Extend the Library Management application.
Add these methods to your BookRepository:
- Find books by author.
- Find books whose titles contain a particular word.
- Update a book's title.
- Delete all books by a particular author.
- Count the total number of books.
Use JdbcTemplate for every operation.
Bonus experiment:
Replace the H2 database with PostgreSQL.
Update your Maven dependencies and application.properties.
Try running the same repository code without changing its SQL queries.
Observe which parts of your application need changes and which parts remain the same.
If this helped, or if you spotted something I should fix, tell me in the comments. I'm still learning too.
Top comments (0)