在本教程中,我们展示了如何使用 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 驱动程序的依赖关系。
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://localhost: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>
在我们称为my-beans.xml的应用上下文 XML 文件中,我们定义了两个 bean:数据源 bean 和jdbcTemplate bean。 数据源 bean 包含数据源属性。 jdbcTemplate通过ref属性引用dataSource bean。 my-beans.xml位于src/main/resources子目录中。
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是为应用提供配置的中央接口。 ClassPathXmlApplicationContext是ApplicationContext的实现,可从位于类路径上的 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)");使用JdbcTemplate's execute()方法,我们创建了Friends表。
jdbcTemplate.update("INSERT INTO Friends VALUES(1, 'Paul', 27)");我们使用JdbcTemplate's update()方法插入一条语句。
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));JdbcTemplate's queryForObject()方法执行 SQL 查询并返回结果对象。 使用BeanPropertyRowMapper将结果对象映射到Friend对象。
List<Friend> allFriends = jdbcTemplate.query("SELECT * FROM Friends", new BeanPropertyRowMapper(Friend.class));allFriends.stream().forEach(System.out::println);使用JdbcTemplate's query()方法,我们检索所有朋友并将其打印到控制台。
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 配置的。
