概述
- 在我们使用普通的 JDBC 数据库时,操作步骤非常麻烦,我们需要写一些不必要的代码来处理异常,打开和关闭数据库连接等。
- Spring JDBC 框架则会帮我们负责所有的低层细节,从开始打开连接,准备和执行 SQL 语句,处理异常,处理事务,到最后关闭连接。所以当从数据库中获取数据时,我们需要做的仅是定义连接参数,指定要执行的 SQL 语句,以及后续操作。
- Spring JDBC 提供几种方法和数据库中相应的不同的类与接口。我将给出使用 JdbcTemplate 类框架的经典和最受欢迎的方法。这是管理所有数据库通信和异常处理的中央框架类。
JdbcTemplate 类
- JdbcTemplate 类执行 SQL 查询、更新语句和存储过程调用,执行迭代结果集和提取返回参数值。它也捕获 JDBC 异常并转换它们到 org.springframework.dao 包中定义的通用类、更多的信息、异常层次结构。
- JdbcTemplate 类的实例是*线程安全* 配置的。所以我们可以配置 JdbcTemplate 的单个实例,然后将这个共享的引用安全地注入到多个 DAOs 中。
- 使用 JdbcTemplate 类时常见的做法是我们在 Spring 配置文件中配置数据源,然后共享数据源 bean 依赖注入到 DAO 类中,并在数据源的设值函数中创建了 JdbcTemplate。
项目环境
配置数据源
- 我们在 MySQL 数据库 spring 中创建一个数据库表 account。
# 创建数据库
CREATE DATABASE spring;
# 使用数据库
USE spring;
# 创建表
CREATE TABLE account(
id INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(40),
money FLOAT
)CHARACTER SET utf8 COLLATE utf8_general_ci;
# 插入数据
INSERT INTO account(NAME,money) VALUES('Cat',1000);
INSERT INTO account(NAME,money) VALUES('Dog',1000);
INSERT INTO account(NAME,money) VALUES('Rat',1000);
Maven依赖
<dependencies>
<!-- spring框架 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<!-- spring JDBC框架 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<!-- mysql数据库 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<!-- junit测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
四种连接方式
目录结构
src
-
main
- java
- cn.water
- Account.java(实体类)
- cn.water
- resources
- Beans.xml(Spring配置文件)
- java
-
test
- cn.water.test
- SpringTest.java(测试类)
- cn.water.test
实体类
Account.java
package cn.water.JDBC;
import java.io.Serializable;
public class Account implements Serializable {
/* 成员变量 */
private Integer id;
private String name;
private Float money;
/* 构造函数 */
public Account() {
}
public Account(Integer id, String name, Float money) {
this.id = id;
this.name = name;
this.money = money;
}
/* 设值函数 */
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Float getMoney() {
return money;
}
public void setMoney(Float money) {
this.money = money;
}
/* toString */
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
'}';
}
}
配置文件
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">
<!-- DriverManagerDataSource -->
<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/spring"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<!-- JdbcTemplate -->
<bean id="jdbc" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
测试类
SpringTest.java
package cn.water.JDBC;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import java.sql.*;
import java.util.List;
public class JDBCTest {
/** Connection对象和Statement对象 */
@Test
public void test01() throws Exception {
/* 1、注册数据库驱动 */
Class.forName("com.mysql.jdbc.Driver");
/* 2、获取Connection对象 */
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/spring", "root", "root");
/* 3、SQL语句 */
String sql = "SELECT * FROM account WHERE id = 1 ";
/* 4、获取Statement对象 */
Statement statement = connection.createStatement();
/* 5、执行SQL语句,并接收结果集 */
ResultSet resultSet = statement.executeQuery(sql);
/* 6、遍历 */
while (resultSet.next()) {
int id = resultSet.getInt(1);
String name = resultSet.getString(2);
float money = resultSet.getFloat(3);
System.out.println("Account:"+id+" "+name+" "+money);
}
}
/** Connection对象和PreparedStatement对象 */
@Test
public void test02() throws Exception {
/* 1、注册 数据库驱动 */
Class.forName("com.mysql.jdbc.Driver");
/* 2、获取 Connection对象 */
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/spring", "root", "root");
/* 3、SQL语句 */
String sql = "SELECT * FROM account WHERE id = ? ";
/* 4、获取 PreparedStatement对象 */
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1,1);
/* 5、执行SQL语句,并接收结果集 */
ResultSet resultSet = preparedStatement.executeQuery();
/* 6、遍历 */
while (resultSet.next()) {
int id = resultSet.getInt(1);
String name = resultSet.getString(2);
float money = resultSet.getFloat(3);
System.out.println("Account:"+id+" "+name+" "+money);
}
}
/** Spring JDBC */
@Test
public void test03() {
/* 1、获取 DriverManagerDataSource对象 */
DriverManagerDataSource dataSource = new DriverManagerDataSource();
/* 2、设置 数据库连接参数 */
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/spring");
dataSource.setUsername("root");
dataSource.setPassword("root");
/* 3、获取 JdbcTemplate对象 */
JdbcTemplate jdbcTemplate = new JdbcTemplate();
/* 4、设值 JdbcTemplate对象 */
jdbcTemplate.setDataSource(dataSource);
/* 5、执行SQL语句,并接收结果集 */
List<Account> result = jdbcTemplate.query(
"SELECT * FROM account WHERE id = ?",
new BeanPropertyRowMapper<Account>(Account.class),
1
);
/* 6、遍历 */
for (Account account : result) {
System.out.println(account);
}
}
/** Spring JDBC + Spring IoC */
@Test
public void test04() {
/* 1、加载配置文件,初始化Bean对象 */
ApplicationContext app = new ClassPathXmlApplicationContext("JDBC/Beans.xml");
/* 2、获取Bean对象 */
JdbcTemplate jdbcTemplate = app.getBean("jdbc", JdbcTemplate.class);
/* 3、执行SQL语句,并接收结果集 */
List<Account> result = jdbcTemplate.query(
"SELECT * FROM account WHERE id = ?",
new BeanPropertyRowMapper<Account>(Account.class),
1
);
/* 5、遍历 */
for (Account account : result) {
System.out.println(account);
}
}
}
Statement
测试类
- 注册数据库驱动:每次手动编写
- 设置数据库连接参数:每次手动编写
- 结果集遍历:麻烦
/* 1、注册数据库驱动 */
Class.forName("com.mysql.jdbc.Driver");
/* 2、获取Connection对象 */
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/spring", "root", "root");
/* 3、SQL语句 */
String sql = "SELECT * FROM account WHERE id = 1 ";
/* 4、获取Statement对象 */
Statement statement = connection.createStatement();
/* 5、执行SQL语句,并接收结果集 */
ResultSet resultSet = statement.executeQuery(sql);
/* 6、遍历 */
while (resultSet.next()) {
int id = resultSet.getInt(1);
String name = resultSet.getString(2);
float money = resultSet.getFloat(3);
System.out.println("Account:"+id+" "+name+" "+money);
}
PreparedStatement
测试类
- 注册数据库驱动:每次手动编写
- 设置数据库连接参数:每次手动编写
- 结果集遍历:麻烦
/* 1、注册 数据库驱动 */
Class.forName("com.mysql.jdbc.Driver");
/* 2、获取 Connection对象 */
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/spring", "root", "root");
/* 3、SQL语句 */
String sql = "SELECT * FROM account WHERE id = ? ";
/* 4、获取 PreparedStatement对象 */
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1,1);
/* 5、执行SQL语句,并接收结果集 */
ResultSet resultSet = preparedStatement.executeQuery();
/* 6、遍历 */
while (resultSet.next()) {
int id = resultSet.getInt(1);
String name = resultSet.getString(2);
float money = resultSet.getFloat(3);
System.out.println("Account:"+id+" "+name+" "+money);
}
JDBC
实体类
public class Account implements Serializable {
/* 成员变量 */
private Integer id;
private String name;
private Float money;
/* 构造函数 */
/* 设值函数 */
/* toString */
}
测试类
- 注册数据库驱动:每次手动编写
- 设置数据库连接参数:每次手动编写
- 结果集遍历:简单
/* 1、获取 DriverManagerDataSource对象 */
DriverManagerDataSource dataSource = new DriverManagerDataSource();
/* 2、设置 数据库连接参数 */
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/spring");
dataSource.setUsername("root");
dataSource.setPassword("root");
/* 3、获取 JdbcTemplate对象 */
JdbcTemplate jdbcTemplate = new JdbcTemplate();
/* 4、设值 JdbcTemplate对象 */
jdbcTemplate.setDataSource(dataSource);
/* 5、执行SQL语句,并接收结果集 */
List<Account> result = jdbcTemplate.query(
"SELECT * FROM account WHERE id = ?",
new BeanPropertyRowMapper<Account>(Account.class),
1
);
/* 6、遍历 */
for (Account account : result) {
System.out.println(account);
}
JDBC 、IoC
实体类
public class Account implements Serializable {
/* 成员变量 */
private Integer id;
private String name;
private Float money;
/* 构造函数 */
/* 设值函数 */
/* toString */
}
配置文件
- 注册数据库驱动:配置文件一次编写
- 数据库连接参数:配置文件一次编写
- 结果集遍历:简单
<!-- DriverManagerDataSource -->
<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/spring"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<!-- JdbcTemplate -->
<bean id="jdbc" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
测试类
/* 1、加载配置文件,初始化Bean对象 */
ApplicationContext app = new ClassPathXmlApplicationContext("JDBC/Beans.xml");
/* 2、获取Bean对象 */
JdbcTemplate jdbcTemplate = app.getBean("jdbc", JdbcTemplate.class);
/* 3、执行SQL语句,并接收结果集 */
List<Account> result = jdbcTemplate.query(
"SELECT * FROM account WHERE id = ?",
new BeanPropertyRowMapper<Account>(Account.class),
1
);
/* 5、遍历 */
for (Account account : result) {
System.out.println(account);
}
三种获取方式
- 三种获取 JdbcTemplate 对象的方法
目录结构
src
-
main
- java
- cn.water
- dao
- AccountDao.java(持久层接口)
- AccountDaoImp01.java(持久层实现类)
- AccountDaoImp02.java(持久层实现类)
- AccountDaoImp03.java(持久层实现类)
- domain
- Account.java(实体类)
- dao
- cn.water
- resources
- Beans.xml(Spring配置文件)
- java
-
test
- cn.water.test
- JDBCTest.java(测试类)
- cn.water.test
实体类
Account.java
package cn.water.JDBCCase.domain;
public class Account {
/* 成员变量 */
private Integer id;
private String name;
private Float money;
/* 构造函数 */
public Account() {
}
public Account(Integer id, String name, Float money) {
this.id = id;
this.name = name;
this.money = money;
}
/* 设值函数 */
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Float getMoney() {
return money;
}
public void setMoney(Float money) {
this.money = money;
}
/* toString */
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
'}';
}
}
持久层
AccontDao.java
package cn.water.JDBCCase.dao;
import cn.water.JDBCCase.domain.Account;
import java.util.List;
public interface AccountDao {
/** 查询所有 */
List<Account> findAll();
/** 查询单个 */
Account findById(Integer id);
}
AccountDaoImp01.java
package cn.water.JDBCCase.dao;
import cn.water.JDBCCase.domain.Account;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;
import java.util.List;
public class AccountDaoImp01 implements AccountDao{
/* 成员变量 */
private DataSource dataSource;
/* 设值函数 */
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
/** 查询所有 */
public List<Account> findAll() {
return new JdbcTemplate(dataSource).query(
"SELECT * FROM account ",
new BeanPropertyRowMapper<Account>(Account.class)
);
}
/** 查询单个 */
public Account findById(Integer id) {
return new JdbcTemplate(dataSource).queryForObject(
"SELECT * FROM account WHERE id = ? ",
new BeanPropertyRowMapper<Account>(Account.class),
id
);
}
}
AccountDaoImp02.java
package cn.water.JDBCCase.dao;
import cn.water.JDBCCase.domain.Account;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import javax.sql.DataSource;
import java.util.List;
public class AccountDaoImp02 implements AccountDao{
/* 成员变量 */
private JdbcTemplate template;
/* 设值函数 */
public void setTemplate(JdbcTemplate template) {
this.template = template;
}
/** 查询所有 */
public List<Account> findAll() {
return template.query(
"SELECT * FROM account ",
new BeanPropertyRowMapper<Account>(Account.class)
);
}
/** 查询单个 */
public Account findById(Integer id) {
return template.queryForObject(
"SELECT * FROM account WHERE id = ? ",
new BeanPropertyRowMapper<Account>(Account.class),
id
);
}
}
AccountDaoImp03.java
package cn.water.JDBCCase.dao;
import cn.water.JDBCCase.domain.Account;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import java.util.List;
public class AccountDaoImp03 extends JdbcDaoSupport implements AccountDao{
/** 查询所有 */
public List<Account> findAll() {
return super.getJdbcTemplate().query(
"SELECT * FROM account ",
new BeanPropertyRowMapper<Account>(Account.class)
);
}
/** 查询单个 */
public Account findById(Integer id) {
return super.getJdbcTemplate().queryForObject(
"SELECT * FROM account WHERE id = ? ",
new BeanPropertyRowMapper<Account>(Account.class),
id
);
}
}
配置文件
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">
<!-- DriverManagerDataSource -->
<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/spring"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<!-- JdbcTemplate -->
<bean id="jdbc" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- DaoImp01 -->
<bean id="dao01" class="cn.water.JDBCCase.dao.AccountDaoImp01">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- DaoImp01 -->
<bean id="dao02" class="cn.water.JDBCCase.dao.AccountDaoImp02">
<property name="template" ref="jdbc"/>
</bean>
<!-- DaoImp02 -->
<bean id="dao03" class="cn.water.JDBCCase.dao.AccountDaoImp03">
<!-- 给父类 -->
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
测试类
JDBCTest.java
package cn.water.JDBCCase;
import cn.water.JDBCCase.dao.AccountDaoImp01;
import cn.water.JDBCCase.dao.AccountDaoImp02;
import cn.water.JDBCCase.domain.Account;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class JDBCTest {
@Test
public void test01(){
ApplicationContext app = new ClassPathXmlApplicationContext("JDBCCase/Beans.xml");
AccountDaoImp01 dao = app.getBean("dao01", AccountDaoImp01.class);
for (Account account : dao.findAll()) {
System.out.println(account);
}
System.out.println(dao.findById(1));
}
@Test
public void test02(){
ApplicationContext app = new ClassPathXmlApplicationContext("JDBCCase/Beans.xml");
AccountDaoImp02 dao = app.getBean("dao02", AccountDaoImp02.class);
for (Account account : dao.findAll()) {
System.out.println(account);
}
System.out.println(dao.findById(1));
}
}
传递DataSource
持久层实现类
- 传递 DataSource后,创建 JdbcTemplate对象,然后调用操作数据库的方法。
/* 成员变量 */
private DataSource dataSource;
/* 设值函数 */
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
/** 查询所有 */
public List<Account> findAll() {
return new JdbcTemplate(dataSource).query(
"SELECT * FROM account ",
new BeanPropertyRowMapper<Account>(Account.class)
);
}
配置文件
<!-- DriverManagerDataSource -->
<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/spring"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<!-- JdbcTemplate -->
<bean id="jdbc" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- DaoImp01 -->
<bean id="dao01" class="cn.water.JDBCCase.dao.AccountDaoImp01">
<!-- 自己用 -->
<property name="dataSource" ref="dataSource"/>
</bean>
传递JdbcTemplate
- 直接传递JdbcTemplate对象,然后调用操作数据库的方法。
持久层实现类
/* 成员变量 */
private JdbcTemplate template;
/* 设值函数 */
public void setTemplate(JdbcTemplate template) {
this.template = template;
}
/** 查询所有 */
public List<Account> findAll() {
return template.query(
"SELECT * FROM account ",
new BeanPropertyRowMapper<Account>(Account.class)
);
}
/** 查询单个 */
public Account findById(Integer id) {
return template.queryForObject(
"SELECT * FROM account WHERE id = ? ",
new BeanPropertyRowMapper<Account>(Account.class),
id
);
}
配置文件
<!-- DriverManagerDataSource -->
<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/spring"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<!-- JdbcTemplate -->
<bean id="jdbc" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- DaoImp02 -->
<bean id="dao02" class="cn.water.JDBCCase.dao.AccountDaoImp02">
<property name="template" ref="jdbc"/>
</bean>
继承父类传递DataSource
继承 JdbcDaoSupport类,并向其传递 DataSource,然后调用父类方法,获取Connection对象,最后执行操作数据库的方法。
持久层实现类
public class AccountDaoImp03 extends JdbcDaoSupport implements AccountDao{
/** 查询所有 */
public List<Account> findAll() {
return super.getJdbcTemplate().query(
"SELECT * FROM account ",
new BeanPropertyRowMapper<Account>(Account.class)
);
}
/** 查询单个 */
public Account findById(Integer id) {
return super.getJdbcTemplate().queryForObject(
"SELECT * FROM account WHERE id = ? ",
new BeanPropertyRowMapper<Account>(Account.class),
id
);
}
}
配置文件
<!-- DriverManagerDataSource -->
<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/spring"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<!-- JdbcTemplate -->
<bean id="jdbc" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- DaoImp03 -->
<bean id="dao03" class="cn.water.JDBCCase.dao.AccountDaoImp03">
<!-- 给父类 -->
<property name="dataSource" ref="dataSource"/>