Spring JDBCTemplate

概述

为了使JDBC更加易于使用,Spring在JDBC API上定义了一个抽象层,以此建立一个JDBC存取框架。
作为Spring JDBC框架的核心,JDBC模板的设计目的是为不同类型的JDBC操作提供模板方法,通过这种方式,可以在尽可能保留灵活性的情况下,将数据库存取的工作量降到最低。
可以将Spring的JdbcTemplate看作是一个小型的轻量级持久化层框架,和我们之前使用过的DBUtils风格非常接近。

环境准备

导包

1) IOC容器所需jar包

1
2
3
4
5
commons-logging-1.1.1.jar
spring-beans-4.0.0.RELEASE.jar
spring-context-4.0.0.RELEASE.jar
spring-core-4.0.0.RELEASE.jar
spring-expression-4.0.0.RELEASE.jar

2) jdbcTemplate所需的jar包

1
2
3
spring-jdbc-4.0.0.RELEASE.jar
spring-orm-4.0.0.RELEASE.jar
spring-tx-4.0.0.RELEASE.jar

3) 数据库驱动和数据源

1
2
c3p0-0.9.1.2.jar
mysql-connector-java-5.1.7-bin.jar

3) 数据库基本信息文件db.properties

1
2
3
4
5
6
7
8
9
10
11
jdbc.user=root
jdbc.password=root
jdbc.jdbcUrl=jdbc:mysql://192.168.37.101:3306/jdbc_template
jdbc.driverClass=com.mysql.jdbc.Driver

jdbc.initialPoolSize=30
jdbc.minPoolSize=10
jdbc.maxPoolSize=100
jdbc.vacquireIncrement=5
jdbc.maxStatements=1000
jdbc.maxStatementsPerConnection=10

4) Spring配置文件

1
2
3
4
5
6
7
8
9
10
11
<context:property-placeholder location="classpath:db.properties"/>
<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="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
<property name="driverClass" value="${jdbc.driverClass}"></property>
</bean>

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg name="dataSource" ref="dataSource"></constructor-arg>
</bean>

持久化操作

  1. 增删改
    JdbcTemplate.update(String, Object…)
    1
    String sql = "UPDATE employee set salary=? WHERE emp_id=?;";int a = template.update(sql, 1345.00, 4);
  2. 批量增删改
  • Object[]封装了SQL语句每一次执行时所需要的参数
  • List集合封装了SQL语句多次执行时的所有参数
    JdbcTemplate.batchUpdate(String, List<Object[]>)
    1
    2
    3
    4
    5
    6
    7
          JdbcTemplate bean = ioc.getBean(JdbcTemplate.class);
    String sql = "INSERT INTO employee(emp_name,salary) VALUES(?,?)";
    List<Object[]> batchArgs = new ArrayList<>();
    batchArgs.add(new Object[] {"boby",11120.00});
    batchArgs.add(new Object[] {"GGBound",10202.00});
    int[] res = bean.batchUpdate(sql, batchArgs);
    System.out.println(Arrays.asList(res));
  1. 查询单行
  • 封装成java对象返回
    JdbcTemplate.queryForObject(String, RowMapper, Object…)
    1
    2
    String sql = "SELECT emp_id, emp_name, salary from employee WHERE emp_id=?";
    Object forObject = bean.queryForObject(sql, new BeanPropertyRowMapper(Employee.class), 5);
  1. 查询多行
  • RowMapper对象依然可以使用BeanPropertyRowMapper
    JdbcTemplate.query(String, RowMapper, Object…)
    1
    2
    String sql = "SELECT emp_id, emp_name, salary from employee WHERE salary>?";
    List query = bean.query(sql, new BeanPropertyRowMapper(Employee.class), 4000);
  1. 查询单一值
  • 查询没结果时会报错
    JdbcTemplate.queryForObject(String, Class, Object…)
    1
    2
          String sql = "SELECT MAX(salary) FROM employee";
    Object forObject = bean.queryForObject(sql, Double.class);

    使用具名参数的JdbcTemplate

  1. 关于具名参数

    在Hibernate的HQL查询中我们体验过具名参数的使用,相对于基于位置的参数,具名参数具有更好的可维护性,在SQL语句中参数较多时可以考虑使用具名参数。
    在Spring中可以通过NamedParameterJdbcTemplate类的对象使用带有具名参数的SQL语句。

  2. 容器创建具名参数的JDBCTemplate对象

    1
    2
    3
    <bean id="namedParameterJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
    <constructor-arg name="dataSource" ref="dataSource"></constructor-arg>
    </bean>
  3. 具名参数传入
    ①通过Map对象传入

  • Map的键是参数名,值是参数值
    NamedParameterJdbcTemplate.update(String, Map<String, ?>)
1
2
3
4
5
      String sql = "INSERT INTO employee(emp_name,salary) VALUES(:empName, :salary)";
Map<String,Object> paramMap = new HashMap<>();
paramMap.put("empName", "cmp");
paramMap.put("salary", 12345.0);
bean.update(sql, paramMap);

②通过SqlParameterSource对象传入

1
2
3
4
5
6
      NamedParameterJdbcTemplate bean = ioc.getBean(NamedParameterJdbcTemplate.class);
String sql = "INSERT INTO employee(emp_name,salary) VALUES(:empName, :salary)";
Employee employee = new Employee();
employee.setEmpName("asdasda");
employee.setSalary("123.123");
bean.update(sql, new BeanPropertySqlParameterSource(employee));

数据库

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/*
SQLyog Ultimate v9.20
MySQL - 5.1.37-community : Database - jdbc_tmeplate
*********************************************************************
*/


/*!40101 SET NAMES utf8 */;

/*!40101 SET SQL_MODE=''*/;

/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`jdbc_template` /*!40100 DEFAULT CHARACTER SET gb2312 */;

USE `jdbc_template`;

/*Table structure for table `employee` */

DROP TABLE IF EXISTS `employee`;

CREATE TABLE `employee` (
`emp_id` int(11) NOT NULL AUTO_INCREMENT,
`emp_name` char(100) DEFAULT NULL,
`salary` double DEFAULT NULL,
PRIMARY KEY (`emp_id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=gb2312;

/*Data for the table `employee` */

insert into `employee`(`emp_id`,`emp_name`,`salary`) values (1,'Susan',5000.23),(2,'Julian',4234.77),(3,'Papu',9034.51),(4,'Babala',8054.33),(5,'Kasier',6039.11),(6,'Owen',7714.11);

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×