JdbcTemplate 简介
- 为了使 JDBC 更加易于使用, Spring 在 JDBC API 上定义了一个抽象层, 以此建立一个 JDBC 存取框架.
- 作为 Spring JDBC 框架的核心, JDBC 模板的设计目的是为不同类型的 JDBC 操作提供模板方法. 每个模板方法都能控制整个过程, 并允许覆盖过程中的特定任务. 通过这种方式, 可以在尽可能保留灵活性的情况下, 将数据库存取的工作量降到最低.
使用 JdbcTemplate 更新数据库
- 用 sql 语句和参数更新数据库
public void testUpdate() {
String sql = "update employee set name = ? where id = ?";
int row = jdbcTemplate.update(sql, "Rose", 4);
System.out.println(row);
}
- 批量更新数据库
public void testBatchUpdate() {
String sql = "insert into employee (name, email, dept_id) values (?, ?, ?)";
List<Object[]> batchArgs = new ArrayList<>();
batchArgs.add(new Object[]{"AA", "[email protected]", 1});
batchArgs.add(new Object[]{"BB", "[email protected]", 3});
batchArgs.add(new Object[]{"CC", "[email protected]", 4});
batchArgs.add(new Object[]{"DD", "[email protected]", 3});
batchArgs.add(new Object[]{"EE", "[email protected]", 2});
int[] result = jdbcTemplate.batchUpdate(sql, batchArgs);
System.out.println(Arrays.toString(result));
}
使用 JdbcTemplate 查询数据库
- 查询单行
public void testQueryForObject() {
String sql = "SELECT id, name, email, dept_id FROM employee WHERE id = ?";
RowMapper<Employee> rowMapper = new BeanPropertyRowMapper<>(Employee.class);
Employee employee = jdbcTemplate.queryForObject(sql, rowMapper, 1);
System.out.println(employee);
}
- 便利的 BeanPropertyRowMapper 实现
- 查询多行
public void testQueryForList() {
String sql = "SELECT id, name, email FROM employee WHERE id > ?";
RowMapper<Employee> rowMapper = new BeanPropertyRowMapper<>(Employee.class);
List<Employee> employees = jdbcTemplate.query(sql, rowMapper, 5);
System.out.println(employees);
}
- 单值查询:
public void testQueryForObject() {
String sql = "SELECT count(id) FROM employee WHERE id > ?";
long count = jdbcTemplate.queryForObject(sql, Long.class, 5);
System.out.println(count);
}
简化 JDBC 模板查询
- 每次使用都创建一个 JdbcTemplate 的新实例, 这种做法效率很低下.
- JdbcTemplate 类被设计成为线程安全的, 所以可以再 IOC 容器中声明它的单个实例, 并将这个实例注入到所有的 DAO 实例中.
- JdbcTemplate 也利用了 Java 1.5 的特定(自动装箱, 泛型, 可变长度等)来简化开发
- Spring JDBC 框架还提供了一个 JdbcDaoSupport 类来简化 DAO 实现. 该类声明了 jdbcTemplate 属性, 它可以从 IOC 容器中注入, 或者自动从数据源中创建.
注入 JDBC 模板示例代码
扩展 JdbcDaoSupport 示例代码
代码示例:
1、数据库表的建立如下:
employee表
department表
2、目录结构
Spring
|——src
|——|——com.hzyc.spring.jdbc
|——|——|——department.java
|——|——|——departmentDao.java
|——|——|——employee.java
|——|——|——employeeDao.java
|——|——|——JdbcTest.java
|——|——application-context.xml
|——|——db.properties
2、db.properties
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql:///spring
jdbc.user=root
jdbc.password=root
jdbc.initPoolSize=5
jdbc.maxPoolSize=10
3、application-context.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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<context:component-scan base-package="com.hzyc.spring"/>
<!--导入资源文件-->
<context:property-placeholder location="classpath:db.properties"/>
<!--配置 c3p0 数据源-->
<bean id="dataSource"
class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driverClass}"/>
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"/>
<property name="user" value="${jdbc.user}"/>
<property name="password" value="${jdbc.password}"/>
<property name="initialPoolSize" value="${jdbc.initPoolSize}"/>
<property name="maxPoolSize" value="${jdbc.maxPoolSize}"/>
</bean>
<!--配置 Spring 的 Jdbc Template-->
<bean id="jdbcTemplate"
class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
department.java
package com.hzyc.spring.jdbc;
/**
* @author xuehj2016
* @Title: Department
* @ProjectName Spring
* @Description: TODO
* @date 2018/12/21 14:43
*/
public class Department {
private int id;
private String name;
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;
}
@Override
public String toString() {
return "Department{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
departmentDao.java
package com.hzyc.spring.jdbc;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;
/**
* @author xuehj2016
* @Title: DepartmentDao
* @ProjectName Spring
* @Description: 不推荐使用 JdbcDaoSupport, 而推荐直接使用 JdbcTemplate 作为 Dao 类的成员变量
* @date 2018/12/21 18:34
*/
@Repository
public class DepartmentDao extends JdbcDaoSupport {
@Autowired
public void setDataSource2(DataSource dataSource) {
setDataSource(dataSource);
}
public Department get(int id) {
String sql = "SELECT id, name FROM department WHERE id = ?";
RowMapper<Department> rowMapper = new BeanPropertyRowMapper<>(Department.class);
return getJdbcTemplate().queryForObject(sql, rowMapper, id);
}
}
employee.java
package com.hzyc.spring.jdbc;
/**
* @author xuehj2016
* @Title: Employee
* @ProjectName Spring
* @Description: TODO
* @date 2018/12/21 14:41
*/
public class Employee {
private int id;
private String name;
private String email;
private Department department;
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 String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", name='" + name + '\'' +
", email='" + email + '\'' +
", department=" + department +
'}';
}
}
employeeDao.java
package com.hzyc.spring.jdbc;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
/**
* @author xuehj2016
* @Title: EmployeeDao
* @ProjectName Spring
* @Description: TODO
* @date 2018/12/21 18:35
*/
@Repository
public class EmployeeDao {
@Autowired
private JdbcTemplate jdbcTemplate;
public Employee get(int id) {
String sql = "SELECT id, name, email FROM employee WHERE id = ?";
RowMapper<Employee> rowMapper = new BeanPropertyRowMapper<>(Employee.class);
Employee employee = jdbcTemplate.queryForObject(sql, rowMapper, id);
return employee;
}
}
JdbcTest.java
package com.hzyc.spring.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.core.RowMapper;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @author xuehj2016
* @Title: JdbcTest
* @ProjectName Spring
* @Description: TODO
* @date 2018/12/21 14:02
*/
public class JdbcTest {
private ApplicationContext applicationContext;
private JdbcTemplate jdbcTemplate;
private EmployeeDao employeeDao;
private DepartmentDao departmentDao;
{
applicationContext = new ClassPathXmlApplicationContext("application-context.xml");
jdbcTemplate = (JdbcTemplate) applicationContext.getBean("jdbcTemplate");
employeeDao = (EmployeeDao) applicationContext.getBean("employeeDao");
departmentDao = (DepartmentDao) applicationContext.getBean("departmentDao");
}
@Test
public void testDataSource() throws SQLException {
DataSource dataSource = (DataSource) applicationContext.getBean("dataSource");
System.out.println(dataSource.getConnection());
}
/**
* 执行 insert ,update , delete
*/
@Test
public void testUpdate() {
String sql = "update employee set name = ? where id = ?";
int row = jdbcTemplate.update(sql, "Rose", 4);
System.out.println(row);
}
/**
* 执行批量更新 : 批量的 insert ,update ,delete
* 最后一个参数是 Object[] 的 List 类型;因为修改一条记录需要一个 Object 的数组,多条就需要多个 Object 的数组
*/
@Test
public void testBatchUpdate() {
String sql = "insert into employee (name, email, dept_id) values (?, ?, ?)";
List<Object[]> batchArgs = new ArrayList<>();
batchArgs.add(new Object[]{"AA", "[email protected]", 1});
batchArgs.add(new Object[]{"BB", "[email protected]", 3});
batchArgs.add(new Object[]{"CC", "[email protected]", 4});
batchArgs.add(new Object[]{"DD", "[email protected]", 3});
batchArgs.add(new Object[]{"EE", "[email protected]", 2});
int[] result = jdbcTemplate.batchUpdate(sql, batchArgs);
System.out.println(Arrays.toString(result));
}
/**
* 从数据库中获取一条记录, 实际得到对应的一个对象
* 注意不是调用 queryForObject(String sql, Class<Employee> requiredType, Object... args) 方法!
* 而需要调用 queryForObject(String sql, RowMapper<Employee> rowMapper, Object... args)
* 1. 其中的 RowMapper 指定如何去映射结果集的行, 常用的实现类为 BeanPropertyRowMapper
* 2. 使用 SQL 中列的别名完成列名和类的属性名的映射. 例如 dept_id as department.id
* 3. 不支持级联属性. JdbcTemplate 到底是一个 JDBC 的小工具, 而不是 ORM 框架
*/
@Test
public void testQueryForObject() {
String sql = "SELECT id, name, email, dept_id FROM employee WHERE id = ?";
RowMapper<Employee> rowMapper = new BeanPropertyRowMapper<>(Employee.class);
Employee employee = jdbcTemplate.queryForObject(sql, rowMapper, 1);
System.out.println(employee);
}
/**
* 查到实体类的集合
* 注意调用的不是 queryForList 方法,而是 query 方法
*/
@Test
public void testQueryForList() {
String sql = "SELECT id, name, email FROM employee WHERE id > ?";
RowMapper<Employee> rowMapper = new BeanPropertyRowMapper<>(Employee.class);
List<Employee> employees = jdbcTemplate.query(sql, rowMapper, 5);
System.out.println(employees);
}
/**
* 获取单个列的值, 或做统计查询
* 使用 queryForObject(String sql, Class<Long> requiredType)
*/
@Test
public void testQueryForObject2() {
String sql = "SELECT count(id) FROM employee WHERE id > ?";
long count = jdbcTemplate.queryForObject(sql, Long.class, 5);
System.out.println(count);
}
@Test
public void testEmployeeDao() {
System.out.println(employeeDao.get(1));
}
@Test
public void testDepartmentDao() {
System.out.println(departmentDao.get(1));
}
}