原文: http://zetcode.com/articles/springjdbctemplate/

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

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

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

    pom.xml

    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <project xmlns="http://maven.apache.org/POM/4.0.0"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
    5. http://maven.apache.org/xsd/maven-4.0.0.xsd">
    6. <modelVersion>4.0.0</modelVersion>
    7. <groupId>com.zetcode</groupId>
    8. <artifactId>SpringJdbcTemplateEx</artifactId>
    9. <version>1.0-SNAPSHOT</version>
    10. <packaging>jar</packaging>
    11. <properties>
    12. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    13. <maven.compiler.source>1.8</maven.compiler.source>
    14. <maven.compiler.target>1.8</maven.compiler.target>
    15. <spring-version>4.3.0.RELEASE</spring-version>
    16. </properties>
    17. <dependencies>
    18. <dependency>
    19. <groupId>mysql</groupId>
    20. <artifactId>mysql-connector-java</artifactId>
    21. <version>5.1.40</version>
    22. </dependency>
    23. <dependency>
    24. <groupId>org.springframework</groupId>
    25. <artifactId>spring-core</artifactId>
    26. <version>${spring-version}</version>
    27. </dependency>
    28. <dependency>
    29. <groupId>org.springframework</groupId>
    30. <artifactId>spring-beans</artifactId>
    31. <version>${spring-version}</version>
    32. </dependency>
    33. <dependency>
    34. <groupId>org.springframework</groupId>
    35. <artifactId>spring-context</artifactId>
    36. <version>${spring-version}</version>
    37. </dependency>
    38. <dependency>
    39. <groupId>org.springframework</groupId>
    40. <artifactId>spring-jdbc</artifactId>
    41. <version>${spring-version}</version>
    42. </dependency>
    43. </dependencies>
    44. </project>

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

    Friend.java

    1. package com.zetcode.bean;
    2. public class Friend {
    3. private int id;
    4. private String name;
    5. private int age;
    6. public int getId() {
    7. return id;
    8. }
    9. public void setId(int id) {
    10. this.id = id;
    11. }
    12. public String getName() {
    13. return name;
    14. }
    15. public void setName(String name) {
    16. this.name = name;
    17. }
    18. public int getAge() {
    19. return age;
    20. }
    21. public void setAge(int age) {
    22. this.age = age;
    23. }
    24. @Override
    25. public String toString() {
    26. return "Friend{" + "id=" + id + ", name=" +
    27. name + ", age=" + age + '}';
    28. }
    29. }

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

    my-beans.xml

    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <beans xmlns="http://www.springframework.org/schema/beans"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xsi:schemaLocation="http://www.springframework.org/schema/beans
    5. http://www.springframework.org/schema/beans/spring-beans.xsd">
    6. <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    7. <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    8. <property name="url" value="jdbc:mysql://localhost:3306/testdb?useSSL=false"/>
    9. <property name="username" value="testuser"/>
    10. <property name="password" value="test623"/>
    11. </bean>
    12. <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    13. <property name="dataSource" ref="dataSource"/>
    14. </bean>
    15. </beans>

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

    SpringJdbcTemplateEx.java

    1. package com.zetcode;
    2. import com.zetcode.bean.Friend;
    3. import java.util.List;
    4. import org.springframework.context.ApplicationContext;
    5. import org.springframework.context.support.ClassPathXmlApplicationContext;
    6. import org.springframework.jdbc.core.BeanPropertyRowMapper;
    7. import org.springframework.jdbc.core.JdbcTemplate;
    8. public class SpringJdbcTemplateEx {
    9. public static void main(String[] args) {
    10. ApplicationContext ctx
    11. = new ClassPathXmlApplicationContext("my-beans.xml");
    12. JdbcTemplate jdbcTemplate = (JdbcTemplate) ctx.getBean("jdbcTemplate");
    13. jdbcTemplate.execute("DROP TABLE IF EXISTS Friends");
    14. jdbcTemplate.execute("CREATE TABLE Friends(Id INT, Name VARCHAR(30), "
    15. + "Age INT)");
    16. jdbcTemplate.update("INSERT INTO Friends VALUES(1, 'Paul', 27)");
    17. jdbcTemplate.update("INSERT INTO Friends VALUES(2, 'Monika', 34)");
    18. jdbcTemplate.update("INSERT INTO Friends VALUES(3, 'Peter', 20)");
    19. jdbcTemplate.update("INSERT INTO Friends VALUES(4, 'Lucy', 45)");
    20. jdbcTemplate.update("INSERT INTO Friends VALUES(5, 'Roman', 57)");
    21. int id = 1;
    22. String sql = "SELECT * FROM Friends WHERE Id=?";
    23. Friend f = (Friend) jdbcTemplate.queryForObject(sql, new Object[]{id},
    24. new BeanPropertyRowMapper(Friend.class));
    25. System.out.println(f);
    26. List<Friend> allFriends = jdbcTemplate.query("SELECT * FROM Friends",
    27. new BeanPropertyRowMapper(Friend.class));
    28. allFriends.stream().forEach(System.out::println);
    29. }
    30. }

    SpringJdbcTemplateEx设置 Spring 应用。

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

    my-beans.xml文件,创建ApplicationContext。 Spring ApplicationContext是为应用提供配置的中央接口。 ClassPathXmlApplicationContextApplicationContext的实现,可从位于类路径上的 XML 文件加载配置定义。

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

    从应用上下文中,我们获得jdbcTemplate bean。

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

    使用JdbcTemplateexecute()方法,我们创建了Friends表。

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

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

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

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

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

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

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

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

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

    这是示例的输出。

    在本教程中,我们创建了一个经典的 Spring 应用,该应用使用JdbcTemplate发出了 SQL 语句。 Spring 应用是用 XML 配置的。 您可能也对这些相关教程感兴趣: JdbcTemplate教程Spring Web 应用简介Spring Boot 第一个 Web 应用Java 教程