本文介绍 JdbcTemplate 的基本概念、环境搭建,以及常用的 CRUD 操作。


一、JdbcTemplate 是什么?

JdbcTemplate 是 Spring 框架提供的一个对象,是对原生 JDBC 的简单封装。Spring 框架为我们提供了很多操作模板类:

模板类适用场景
JdbcTemplate操作关系型数据库(JDBC)
HibernateTemplate操作关系型数据库(Hibernate)
RedisTemplate操作 NoSQL 数据库(Redis)
JmsTemplate操作消息队列(JMS)

JdbcTemplate 的主要作用:与数据库交互,实现数据表的 CRUD 操作

它的核心代码在 spring-jdbc 包中,同时还需要引入 spring-tx(事务相关包)。


二、环境搭建

2.1 引入依赖

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.0.2.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.0.2.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>5.0.2.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.6</version>
    </dependency>
</dependencies>

2.2 创建实体类

public class Account {
    private Integer id;
    private String name;
    private Double money;

    // getter/setter 省略

    @Override
    public String toString() {
        return "Account{id=" + id + ", name='" + name + "', money=" + money + "}";
    }
}

2.3 最基础的使用方式

public class JdbcTemplateDemo1 {
    public static void main(String[] args) {
        JdbcTemplate jt = new JdbcTemplate();
        jt.execute("insert into account(name, money) values('Oneal', 100.0)");
    }
}

直接 new JdbcTemplate() 使用时,需要手动配置数据源。当我们看到有 newset 操作时,就应该想到:可以用 Spring 的 IOC 来配置,让 Spring 管理数据源和 JdbcTemplate 对象。


三、在 Spring IOC 中使用 JdbcTemplate

3.1 创建 bean.xml 配置文件

<!-- 配置数据源(使用 Spring 内置数据源) -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
    <property name="url" value="jdbc:mysql://localhost:3306/ssm"></property>
    <property name="username" value="root"></property>
    <property name="password" value="Admin123!"></property>
</bean>

<!-- 配置 JdbcTemplate,注入数据源 -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    <property name="dataSource" ref="dataSource"></property>
</bean>

3.2 测试类

public class JdbcTemplateDemo2 {
    public static void main(String[] args) {
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        JdbcTemplate jt = ac.getBean("jdbcTemplate", JdbcTemplate.class);
        jt.execute("insert into account(name, money) values('kobe', 500.0)");
    }
}

通过 IOC 容器获取 JdbcTemplate,数据源的配置由 Spring 统一管理,更加优雅。


四、JdbcTemplate 的 CRUD 操作

4.1 增删改操作(update 方法)

JdbcTemplateupdate() 方法用于执行 INSERT、UPDATE、DELETE:

// 新增
jt.update("insert into account(name, money) values(?, ?)", "james", 1000.0);

// 修改
jt.update("update account set money = ? where name = ?", 800.0, "james");

// 删除
jt.update("delete from account where id = ?", 1);

4.2 查询操作

查询需要用到 RowMapper,它是一个接口,负责将 ResultSet 的每一行映射为一个 Java 对象。

自定义 RowMapper:

public class AccountRowMapper implements RowMapper<Account> {
    /**
     * 把结果集中的数据封装到 Account 对象中
     * Spring 会自动把每个 Account 放入集合
     */
    public Account mapRow(ResultSet rs, int i) throws SQLException {
        Account account = new Account();
        account.setId(rs.getInt("id"));
        account.setName(rs.getString("name"));
        account.setMoney(rs.getDouble("money"));
        return account;
    }
}
4.2.1 查询所有
List<Account> accounts = jt.query(
    "select * from account where money > ?",
    new AccountRowMapper(),
    100.0
);
for (Account account : accounts) {
    System.out.println(account);
}
4.2.2 查询单个
List<Account> accounts = jt.query(
    "select * from account where name = ?",
    new AccountRowMapper(),
    "james"
);
System.out.println(accounts.get(0));

💡 Spring 也内置了 BeanPropertyRowMapper,能自动完成字段名到属性的映射(要求字段名与属性名一致):

new BeanPropertyRowMapper<>(Account.class)
4.2.3 聚合函数查询
Long count = jt.queryForObject(
    "select count(*) from account where money > ?",
    Long.class,
    100.0
);
System.out.println(count);

五、JdbcTemplate 在 Dao 中的使用

在实际项目中,JdbcTemplate 通常注入到 DAO 层使用。

5.1 定义 DAO 接口

public interface AccountDao {
    Account findAccountById(Integer accountId);
    Account findAccountByName(String accountName);
    void updateAccount(Account account);
}

5.2 编写 DAO 实现类

public class AccountDaoImpl implements AccountDao {

    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public Account findAccountById(Integer accountId) {
        List<Account> accounts = jdbcTemplate.query(
            "select * from account where id=?",
            new AccountRowMapper(),
            accountId
        );
        return accounts.get(0);
    }

    public Account findAccountByName(String accountName) {
        List<Account> accounts = jdbcTemplate.query(
            "select * from account where name=?",
            new AccountRowMapper(),
            accountName
        );
        return accounts.get(0);
    }

    public void updateAccount(Account account) {
        jdbcTemplate.update(
            "update account set name=?, money=? where id=?",
            account.getName(), account.getMoney(), account.getId()
        );
    }
}

5.3 配置文件

<!-- 配置 DAO,注入 JdbcTemplate -->
<bean id="accountDao" class="com.xq.dao.impl.AccountDaoImpl">
    <property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>

<!-- 配置 JdbcTemplate,注入数据源 -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    <property name="dataSource" ref="dataSource"></property>
</bean>

<!-- 配置数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
    <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/ssm"></property>
    <property name="user" value="root"></property>
    <property name="password" value="Admin123!"></property>
</bean>

六、小结

JdbcTemplate 是 Spring 对 JDBC 的简洁封装,解决了原生 JDBC 大量重复的模板代码问题。

方法用途
execute(sql)执行任意 SQL(DDL 等)
update(sql, args...)增删改操作
query(sql, rowMapper, args...)查询列表
queryForObject(sql, type, args...)查询单值(聚合函数)

在 Spring 项目中,通过 IOC 将 JdbcTemplate 和数据源统一配置,再注入到 DAO 层使用,是标准的开发实践。

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐