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
- Add JDBC dependencies
- Configure the database connection
- Understanding JDBC
- The JDBC building blocks
- A small JDBC program
- Why Spring provides JdbcTemplate
- What JdbcTemplate takes care of
- Querying rows with RowMapper
- Inserting updating and deleting rows
- Understanding placeholders and SQL injection
- Initialize the database with schema.sql
- Create the books table
- How Spring Boot finds schema.sql
- Insert starter data with data.sql
- Add sample books
- Control when SQL scripts run
- Put everything together
- Book model
- Repository using JdbcTemplate
- Run the application
- What else should you know?
- JDBC versus JdbcTemplate versus Spring Data JPA
- When to use Flyway or Liquibase
- 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:
Source:https://dev.to/mayur_bodhare/jdbc-and-jdbctemplate-explained-database-access-in-spring-boot-mi9Related posts
I Built an Education App: Here’s What I Learned About Scalability
Travel Agency Booking Portals: Building Scalable B2B/B2C Platforms for the Modern Traveler
Retail ERP & POS Software: Why Off-the-Shelf Solutions Fail Growing Businesses in MENA
