JdbcTemplate简介
- 为了使JDBC更加易于使用,Spring在JDBC API上定义了一个抽象层,以此建立一个JDBC存取框架
- 作为Spring JDBC框架的核心,JDBC模板的设计目的是为不同类型的JDBC操作提供模板方法,每个模板方法都能控制整个过程,并允许覆盖过程中的特定任务。通过这种方式,可以在尽可能保留灵活性的情况下,将数据库存取的工作量降到最低。
代码示例:
首先是数据库的配置。数据库中包含employee和department两张表。
1.jdbc.properties文件
jdbc.user=scott
jdbc.password=tiger
jdbc.driverClass=oracle.jdbc.driver.OracleDriver
jdbc.jdbcUrl=jdbc:oracle:thin:@localhost:1521:orcl
jdbc.initialPoolSize=5
jdbc.maxPoolSize=10
2. spring的配置文件
<?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.1.xsd">
<context:component-scan base-package="com.yl.spring.jdbc"></context:component-scan>
<!-- 导入属性文件 -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 配置c3p0数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
<property name="initialPoolSize" value="${jdbc.initialPoolSize}"></property>
<property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
</bean>
<!-- 配置Spring的JdbcTemplate -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
</beans>
package com.yl.spring.jdbc;
public class Employee {
private Integer id;
private String lastName;
private String email;
private Department department;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
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 + ", lastName=" + lastName + ", email="
+ email + ", department=" + department + "]";
}
}
package com.yl.spring.jdbc;
public class Department { private Integer id; private String name; 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; } @Override public String toString() { return "Department [id=" + id + ", name=" + name + "]"; } }
package com.yl.spring.jdbc;
import Java.sql.SQLException; import Java.util.ArrayList; import Java.util.List; import Javax.sql.DataSource; 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; public class JDBCTest { private ApplicationContext ctx = null; private JdbcTemplate jdbcTemplate; private EmployeeDao employeeDao; { ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); jdbcTemplate = (JdbcTemplate)ctx.getBean("jdbcTemplate"); employeeDao = ctx.getBean(EmployeeDao.class); } @Test public void testEmployeeDao() { System.out.println(employeeDao.get(1)); } /** * 获取单个列的值,或做统计查询 */ @Test public void testQueryForObject2() { String sql = "SELECT count(id) FROM employee"; long count = jdbcTemplate.queryForObject(sql, Long.class); System.out.println(count); } /** * 查到实体类的集合 */ @Test public void testQueryForList() { String sql = "SELECT id, last_name, email FROM employee WHERE id > ?"; RowMapper<Employee> rowMapper = new BeanPropertyRowMapper<Employee>(Employee.class); List<Employee> employees = jdbcTemplate.query(sql, rowMapper, 5); System.out.println(employees); } /** * 从数据库中获取一条记录,实际得到对应的一个对象 * 1.RowMapper指定如何映射结果集的行,常用的实现类为BeanPropertyRowMapper * 2.使用SQL中列的别名完成列名和类的属性名的映射。例如last_name和lastName * 3.不支持级联属性。JdbcTemplate到底是一个JDBC工具,不是ORM框架。 */ @Test public void TestForQueryObject() { String sql = "SELECT id, last_name, email FROM employee WHERE id = ?"; RowMapper<Employee> rowMapper = new BeanPropertyRowMapper<Employee>(Employee.class); Employee employee = jdbcTemplate.queryForObject(sql, rowMapper, 1); System.out.println(employee); } /** * 批量执行更新:批量的INSERT, UPDATE, DELETE * 最后一个参数是Object[]的list类型:因为修改一条记录需要一个Object的数组,那么多条就是需要多个Object的数组 */ @Test public void testBatchUpdate() { String sql = "INSERT INTO employee(id, last_name, email, dept_id) VALUES(?, ?, ?, ?)"; List<Object[]> batchArgs = new ArrayList<Object[]>(); batchArgs.add(new Object[]{6, "AA", "[email protected]", 1}); batchArgs.add(new Object[]{7, "BB", "[email protected]", 2}); batchArgs.add(new Object[]{8, "CC", "[email protected]", 3}); batchArgs.add(new Object[]{9, "DD", "[email protected]", 3}); batchArgs.add(new Object[]{10, "EE", "[email protected]", 2}); jdbcTemplate.batchUpdate(sql, batchArgs); } /** * 执行INSERT, UPDATE, DELETE */ @Test public void testUpdate() { String sql = "UPDATE employee SET last_name=? WHERE id=?"; jdbcTemplate.update(sql, "Jack", 5); } @Test public void test() throws SQLException { DataSource dataSource = (DataSource)ctx.getBean("dataSource"); System.out.println(dataSource.getConnection()); } }