ZetCode

经典 Spring 应用程序中的 JdbcTemplate

最后修改于 2020 年 7 月 13 日

在本教程中,我们将展示如何使用 JdbcTemplate 创建一个经典的 Spring 应用程序。该应用程序连接到 MySQL 数据库,并使用 JdbcTemplate 发出 SQL 语句。

Spring 是一个流行的 Java 应用程序框架,用于用 Java 开发企业应用程序。它也是一个非常好的集成系统,有助于将各种企业组件粘合在一起。

JdbcTemplate 是一个库,可帮助程序员创建处理关系数据库和 JDBC 的应用程序。它处理许多耗时且容易出错的底层细节,例如处理事务、清理资源和正确处理异常。JdbcTemplate 包含在 Spring 的 spring-jdbc 模块中。

pom.xml
<?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.zetcode</groupId>
    <artifactId>SpringJdbcTemplateEx</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    
    <properties>
        
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <spring-version>4.3.0.RELEASE</spring-version>
        
    </properties>
    
    <dependencies>
        
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.40</version>
        </dependency>        
        
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring-version}</version>
        </dependency>
        
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring-version}</version>
        </dependency>
        
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring-version}</version>
        </dependency>
        
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring-version}</version>
        </dependency>
    
    </dependencies>    

</project>

在 Maven 构建文件中,我们提供了 Spring 应用程序核心、JdbcTemplate 库和 MySQL 驱动程序的依赖项。

com/zetcode/Friend.java
package com.zetcode.bean;

public class Friend {

    private int id;
    private String name;
    private int age;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

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

这是一个 Friend 类。数据库表中的一行将映射到此类。

my-beans.xml
<?xml version="1.0" encoding="UTF-8"?>

<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="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://:3306/testdb?useSSL=false"/>
        <property name="username" value="testuser"/>
        <property name="password" value="test623"/>
    </bean>
    
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>    
    
</beans>

在应用程序上下文 XML 文件(我们称之为 my-beans.xml)中,我们定义了两个 bean:数据源 bean 和 jdbcTemplate bean。数据源 bean 包含数据源属性;jdbcTemplate 通过 ref 属性引用 dataSource bean。my-beans.xml 位于 src/main/resources 子目录中。

com/zetcode/SpringJdbcTemplateEx.java
package com.zetcode;

import com.zetcode.bean.Friend;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

public class SpringJdbcTemplateEx {

    public static void main(String[] args) {

        ApplicationContext ctx
                = new ClassPathXmlApplicationContext("my-beans.xml");

        JdbcTemplate jdbcTemplate = (JdbcTemplate) ctx.getBean("jdbcTemplate");

        jdbcTemplate.execute("DROP TABLE IF EXISTS Friends");
        jdbcTemplate.execute("CREATE TABLE Friends(Id INT, Name VARCHAR(30), "
                + "Age INT)");
        jdbcTemplate.update("INSERT INTO Friends VALUES(1, 'Paul', 27)");
        jdbcTemplate.update("INSERT INTO Friends VALUES(2, 'Monika', 34)");
        jdbcTemplate.update("INSERT INTO Friends VALUES(3, 'Peter', 20)");
        jdbcTemplate.update("INSERT INTO Friends VALUES(4, 'Lucy', 45)");
        jdbcTemplate.update("INSERT INTO Friends VALUES(5, 'Roman', 57)");

        int id = 1;
        String sql = "SELECT * FROM Friends WHERE Id=?";

        Friend f = (Friend) jdbcTemplate.queryForObject(sql, new Object[]{id},
                new BeanPropertyRowMapper(Friend.class));

        System.out.println(f);

        List<Friend> allFriends = jdbcTemplate.query("SELECT * FROM Friends",
                new BeanPropertyRowMapper(Friend.class));
        
        allFriends.stream().forEach(System.out::println);
    }
}

SpringJdbcTemplateEx 设置了 Spring 应用程序。

ApplicationContext context = 
        new ClassPathXmlApplicationContext("my-beans.xml");

通过 my-beans.xml 文件,我们创建了 ApplicationContext。Spring ApplicationContext 是提供应用程序配置的核心接口。ClassPathXmlApplicationContextApplicationContext 的一个实现,它从类路径上的 XML 文件加载配置定义。

JdbcTemplate jdbcTemplate = (JdbcTemplate) ctx.getBean("jdbcTemplate");

从应用程序上下文中,我们获取 jdbcTemplate bean。

jdbcTemplate.execute("DROP TABLE IF EXISTS Friends");
jdbcTemplate.execute("CREATE TABLE Friends(Id INT, Name VARCHAR(30), "
        + "Age INT)");

使用 JdbcTemplateexecute 方法,我们创建了一个 Friends 表。

jdbcTemplate.update("INSERT INTO Friends VALUES(1, 'Paul', 27)");

我们使用 JdbcTemplateupdate 方法插入一条语句。

int id = 1;
String sql = "SELECT * FROM Friends WHERE Id=?";

在此 SQL 语句中,我们选择由其 ID 标识的朋友。

Friend f = (Friend) jdbcTemplate.queryForObject(sql, new Object[]{id},
        new BeanPropertyRowMapper(Friend.class));

JdbcTemplatequeryForObject 方法执行 SQL 查询并返回结果对象。使用 BeanPropertyRowMapper 将结果对象映射到 Friend 对象。

List<Friend> allFriends = jdbcTemplate.query("SELECT * FROM Friends",
        new BeanPropertyRowMapper(Friend.class));

allFriends.stream().forEach(System.out::println);

使用 JdbcTemplatequery 方法,我们检索所有朋友并将它们打印到控制台。

Friend{id=1, name=Paul, age=27}
Friend{id=1, name=Paul, age=27}
Friend{id=2, name=Monika, age=34}
Friend{id=3, name=Peter, age=20}
Friend{id=4, name=Lucy, age=45}
Friend{id=5, name=Roman, age=57}

在本教程中,我们创建了一个经典的 Spring 应用程序,该应用程序使用 JdbcTemplate 发出了 SQL 语句。Spring 应用程序在 XML 中配置。