Backend Development 26 min read

Spring JdbcTemplate Tutorial: Environment Setup, CRUD Operations, and Advanced Features

This tutorial demonstrates how to configure Spring 6 with JdbcTemplate, create a MySQL database and table, define entity and datasource beans, and perform CRUD operations—including batch updates and callback functions—while also showing integration with the Druid connection pool.

Java Captain
Java Captain
Java Captain
Spring JdbcTemplate Tutorial: Environment Setup, CRUD Operations, and Advanced Features

This article provides a step‑by‑step guide for using Spring's JdbcTemplate to access a MySQL database, covering environment preparation, bean configuration, and various data‑access techniques.

Environment preparation : Create a Maven module with Spring 6 (JDK 17) and add the required dependencies (spring‑context, mysql‑connector‑java, spring‑jdbc, junit).

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.rainbowsea</groupId>
    <artifactId>spring6-009-jdbc-blog</artifactId>
    <version>1.0-SNAPSHOT</version>
    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>6.0.11</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.30</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>6.0.0-M2</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

Database setup : Create a MySQL database spring6 and a table user with columns id , real_name , and age . Sample SQL:

CREATE DATABASE IF NOT EXISTS spring6;
CREATE TABLE `user` (
    `id` int NOT NULL AUTO_INCREMENT,
    `real_name` varchar(255),
    `age` int,
    PRIMARY KEY (`id`) USING BTREE
);

Entity class (User):

package com.rainbowsea.spring6.bean;

public class User {
    private Integer id;
    private String realName;
    private Integer age;
    // constructors, getters, setters, toString()
}

Custom DataSource implementation (MyDataSource) that implements javax.sql.DataSource and provides getConnection() by loading the driver and calling DriverManager.getConnection :

package com.rainbowsea.spring6.bean;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class MyDataSource implements DataSource {
    private String driver;
    private String url;
    private String userName;
    private String password;
    // setters, getters, toString()
    @Override
    public Connection getConnection() throws SQLException {
        try {
            Class
clazz = Class.forName(driver);
            Connection connection = DriverManager.getConnection(url, userName, password);
            System.out.println(connection);
            return connection;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    // other DataSource methods omitted for brevity
}

Spring bean configuration (spring.xml) registers the custom datasource and the JdbcTemplate:

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="dataSource" class="com.rainbowsea.spring6.bean.MyDataSource">
        <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/spring6"/>
        <property name="userName" value="root"/>
        <property name="password" value="123"/>
    </bean>
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>
</beans>

CRUD examples using JdbcTemplate (JUnit test class):

public class JdbcTest {
    @Test
    public void testInsert() {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("spring6.xml");
        JdbcTemplate jt = ctx.getBean("jdbcTemplate", JdbcTemplate.class);
        String sql = "insert into user(real_name,age) values(?,?)";
        int count = jt.update(sql, "张三", 30);
        System.out.println("Inserted rows: " + count);
    }
    @Test
    public void testUpdate() {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("spring6.xml");
        JdbcTemplate jt = ctx.getBean("jdbcTemplate", JdbcTemplate.class);
        String sql = "update user set real_name = ?, age = ? where id = ?";
        int count = jt.update(sql, "张小六", 18, 1);
        System.out.println("Updated rows: " + count);
    }
    @Test
    public void testDelete() {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("spring6.xml");
        JdbcTemplate jt = ctx.getBean("jdbcTemplate", JdbcTemplate.class);
        String sql = "delete from user where id = ?";
        int count = jt.update(sql, 4);
        System.out.println("Deleted rows: " + count);
    }
}

Querying a single object with queryForObject and BeanPropertyRowMapper :

User user = jdbcTemplate.queryForObject(
    "select id, real_name, age from user where id = ?",
    new BeanPropertyRowMapper<>(User.class),
    1);
System.out.println(user);

Querying a single value (e.g., row count):

Integer count = jdbcTemplate.queryForObject(
    "select count(1) from user",
    int.class);
System.out.println(count);

Batch operations (insert, update, delete) using batchUpdate with a List<Object[]> of parameter arrays:

String sql = "insert into user(real_name,age) values(?,?)";
List
batch = new ArrayList<>();
batch.add(new Object[]{"小花", 20});
batch.add(new Object[]{"小明", 21});
batch.add(new Object[]{"小刚", 22});
int[] results = jdbcTemplate.batchUpdate(sql, batch);
System.out.println(Arrays.toString(results));

Using a callback with jdbcTemplate.execute and PreparedStatementCallback to manually process a ResultSet :

User user = jdbcTemplate.execute(
    "select id,real_name,age from user where id = ?",
    (PreparedStatementCallback
) ps -> {
        ps.setInt(1, 2);
        ResultSet rs = ps.executeQuery();
        if (rs.next()) {
            return new User(rs.getInt("id"), rs.getString("real_name"), rs.getInt("age"));
        }
        return null;
    });
System.out.println(user);

Integration with Druid connection pool : add the Druid dependency and configure a DruidDataSource bean in spring.xml (using driverClassName , url , username , password ) and reference it from the JdbcTemplate.

<bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource">
    <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost:3306/spring6"/>
    <property name="username" value="root"/>
    <property name="password" value="123"/>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    <property name="dataSource" ref="druidDataSource"/>
</bean>

The article concludes by summarizing that JdbcTemplate simplifies JDBC operations, supports standard CRUD, batch processing, and callback mechanisms, and can be combined with external connection pools such as Druid for production‑grade performance.

backendJavaDatabaseSpringCRUDJdbcTemplate
Java Captain
Written by

Java Captain

Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.