一、说明

1.Spring JDBC 对原始的 JDBC 进行了封装,使其更加易用。

2.JdbcTemplate 作为 Spring JDBC 的核心,为不同类型的 JDBC 操作提供了模板方法。

3.JdbcTemplate 对于 Spring 作用与 DbUtils 对于 Jdbc 的意义相同。它们做的是同一件事情。

二、JdbcTemplate

1.在 Spring Config 文件中注册 JdbcTemplate 的实例,同时配置数据源,如:

<context:property-placeholder location="classpath:db.properties"/>

<bean class="com.mchange.v2.c3p0.ComboPooledDataSource" id="dataSource">
  <property name="driverClass" value="${jdbc.driverClass}"/>
  <property name="jdbcUrl" value="${jdbc.jdbcUrl}"/>
  <property name="user" value="${jdbc.user}"/>
  <property name="password" value="${jdbc.password}"/>
</bean> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
  <property name="dataSource" ref="dataSource"/>
</bean>

2.在目标类中,注入 JdbcTemplate 实例,进行相应的 Jdbc 操作。

/**
* @author solverpeng
* @create 2016-07-28-20:29
*/
@Repository
public class StudentDao {
@Autowired
private JdbcTemplate jdbcTemplate;
}

3.更新(增、删、改)和批量更新,这里只作一个类型的例子。

(1)增,返回受影响的行数

StudentDao:

public void insertStudent() {
  String sql = "insert into student(student_id, student_name, student_class) " +
      "values(?,?,?)";
  int affectRows = this.jdbcTemplate.update(sql, 1, "tom", "0102");
  System.out.println("affectRows:" + affectRows);
}

控制台输出:

affectRows:1

(2)增,返回增加的主键值

StudentDao:

public void insertStudent2() {
  PreparedStatementCreator psc = new PreparedStatementCreator() {
    @Override
    public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
      String sql = "insert into student(student_id, student_name, student_class) values(?, ?, ?)";
      PreparedStatement ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
      ps.setInt(1, 2);
      ps.setString(2, "jerry");
      ps.setString(3, "0805");
      return ps;
    }
  };
  KeyHolder keyHolder = new GeneratedKeyHolder();
  this.jdbcTemplate.update(psc, keyHolder);
  Number key = keyHolder.getKey();
  System.out.println(key);
}

数据库:

控制台输出:

2

在做这个测试的时候遇到一个问题:!Statement.GeneratedKeysNotRequested!

解决:http://stackoverflow.com/questions/7162989/sqlexception-generated-keys-not-requested-mysql

(3)批量增

StudentDao:

public void batchUpdate() {
  String sql = "insert into student(student_id, student_name, student_class) values(?, ?, ?)";
  List<Object[]> list = new ArrayList<>();
  list.add(new Object[]{3, "lily", "0806"});
  list.add(new Object[]{4, "lucy", "0807"});
  this.jdbcTemplate.batchUpdate(sql, list);
}

数据库:

4.查询单个对象:queryForObject

StudentDao:

public void getStudent(Integer id) {
  String sql = "select student_id, student_name, student_class from student where student_id = ?";
  RowMapper<Student> rowMapper = new BeanPropertyRowMapper<>(Student.class);
  Student student = this.jdbcTemplate.queryForObject(sql, rowMapper, id);
  System.out.println(student);
}

控制台输出:

Student{studentId=1, studentName='tom', studentClass='0804'}

5.返回查询的记录数

public void getCount() {
  String sql = "select count(student_id) from student";
  Long count = this.jdbcTemplate.queryForObject(sql, Long.class);
  System.out.println(count);
}

控制台输出:

4

三、NamedParameterJdbcTemplate :在 sql 中嵌入命名参数。

1.同样在 Spring Config 文件中进行配置

2.使用 ParamMap 插入

StudentDao:

public void insert() {
  String sql = "insert into student(student_id, student_name, student_class) values(:studentId, :studentName, :studentClass)";
  Map<String, Object> paramMap = new HashMap<>();
  paramMap.put("studentId", 5);
  paramMap.put("studentName", "jakc");
  paramMap.put("studentClass", "0808");
  this.namedParameterJdbcTemplate.update(sql, paramMap);
}

数据库:

3.使用 SqlParameterSource 插入

public void insert2() {
  String sql = "insert into student(student_id, student_name, student_class) values(:studentId, :studentName, :studentClass)";
  Student student = new Student();
  student.setStudentId(6);
  student.setStudentName("mary");
  student.setStudentClass("0809");
  SqlParameterSource source = new BeanPropertySqlParameterSource(student);
  this.namedParameterJdbcTemplate.update(sql, source);
}

数据库:

4.使用 SqlParameterSource 插入返回主键

public void insert3() {
  String sql = "insert into student(student_id, student_name, student_class) values(:studentId, :studentName, :studentClass)";
  Student student = new Student();
  student.setStudentId(7);
  student.setStudentName("kobe");
  student.setStudentClass("0810");
  SqlParameterSource source = new BeanPropertySqlParameterSource(student);
  KeyHolder keyHolder = new GeneratedKeyHolder();
  this.namedParameterJdbcTemplate.update(sql,source, keyHolder);
  Number key = keyHolder.getKey();
  System.out.println(key);
}

控制台输出:

7

数据库:

四、继承 JdbcDaoSupport

1.继承 JdbcDaoSupport,需要为每一个目标类配置数据源,JdbcTemplate会自动注入,不需要在SpringConfig文件中配置JdbcTemplate。

2.需要注意的是,不能在目标类中通过 @Autowired 的方式注入 dataSource。

3.演示一个例子:

/**
* @author solverpeng
* @create 2016-07-29-11:29
*/
@Repository
public class PersonDao extends JdbcDaoSupport{
public void insert() {
String sql = "insert into person(id, person_name) values(?, ?)";
this.getJdbcTemplate().update(sql, 1, "tom");
}
}

SpringConfig文件:

<bean class="com.nucsoft.spring.jdbc.PersonDao" id="dao">
<property name="dataSource" ref="dataSource"/>
</bean>

Spring应用——对 JDBC 的支持的更多相关文章

  1. Spring项目对JDBC的支持和基本使用

    欢迎查看Java开发之上帝之眼系列教程,如果您正在为Java后端庞大的体系所困扰,如果您正在为各种繁出不穷的技术和各种框架所迷茫,那么本系列文章将带您窥探Java庞大的体系.本系列教程希望您能站在上帝 ...

  2. 开涛spring3(7.5) - 对JDBC的支持 之 7.5 集成Spring JDBC及最佳实践

    7.5 集成Spring JDBC及最佳实践 大多数情况下Spring JDBC都是与IOC容器一起使用.通过配置方式使用Spring JDBC. 而且大部分时间都是使用JdbcTemplate类(或 ...

  3. 1.Spring对JDBC整合支持

    1.Spring对JDBC整合支持 Spring对DAO提供哪些支持 1)Spring对DAO异常提供统一处理 2)Spring对DAO编写提供支持的抽象类 3)提高编程效率,减少DAO编码量 Spr ...

  4. Spring 对JDBC操作的支持

    1.Spring 对JDBC操作的支持 Spring对jdbc技术提供了很好的支持,体现在: 1.Spring对c3p0连接池的支持很完善 2.Spring对jdbc提供了jdbcTemplate,来 ...

  5. 8.Spring对JDBC的支持和事务

    1.Spring对JDBC的支持 DAO : Spring中对数据访问对象(DAO)的支持旨在简化Spring与数据访问技术的操作,使JDBC.Hibernate.JPA和JDO等采用统一的方式访问 ...

  6. Spring 中的 JDBC 事务

    Spring 对 JDBC 的支持 JdbcTemplate 简介 •为了使 JDBC 更加易于使用, Spring 在 JDBC API 上定义了一个抽象层, 以此建立一个 JDBC 存取框架. • ...

  7. 使用Spring JDBCTemplate简化JDBC的操作

    使用Spring JDBCTemplate简化JDBC的操作 接触过JAVA WEB开发的朋友肯定都知道Hibernate框架,虽然不否定它的强大之处,但个人对它一直无感,总感觉不够灵活,太过臃肿了. ...

  8. 开涛spring3(6.9) - 对JDBC的支持 之 7.1 概述

    7.1  概述 7.1.1  JDBC回顾 传统应用程序开发中,进行JDBC编程是相当痛苦的,如下所示: //cn.javass.spring.chapter7. TraditionalJdbcTes ...

  9. Spring 对事务管理的支持

    1.Spring对事务管理的支持 Spring为事务管理提供了一致的编程模板,在高层次建立了统一的事务抽象.也就是说,不管选择Spring JDBC.Hibernate .JPA 还是iBatis,S ...

随机推荐

  1. Jmeter调试工具---HTTP Mirror Server

    之前我介绍过Jmeter的一种调试工具Debug Sampler,它可以输出Jmeter的变量.属性甚至是系统属性而不用发送真实的请求到服务器.既然这样,那么HTTP Mirror Server又是做 ...

  2. WPF UI虚拟化

    ComboBox

  3. EF Repository Update

    问题描述: 解决办法: http://www.cnblogs.com/scy251147/p/3688844.html 原理: Attaching an entity of type '' faile ...

  4. Ecshop文章列表页显示内容摘要

    本教程中讲到的“内容摘要”指的是文章内容的前 60个字符(当然也可以是前40个,前50个等等) 下面以 2.7.2版 + 官方默认模板 为例进行讲解: 1).修改 includes/lib_artic ...

  5. Android上面安装Linux的方法

    方法一: 并行安装Linux(不在Android操作系统之上运行,需要设备已经unlocked并且rooted) 我还没玩过.放两个书签: How to Install Ubuntu on Andro ...

  6. 找回Win8.1(windows server 2012 R2)的双拼

    一.微软拼音的选项,只能在metro界面修改: 鼠标移动到屏幕右下,出现metro的菜单,选"设置"然后选最下面的"更改电脑设置" 时间和设置->区域和语 ...

  7. Golang pprof heap profile is empty

    Q: When you use `go tool pprof` get heap data, profile is empty. A: The default sampling rate is 1 s ...

  8. Mvc 拼接Html 导出 Excel(服务器不用安装呦!支持2007以上版本)

    新公司,新接触,老方法,更实用. 之前接触过Webform,winfrom 的导出Excel方法 ,优点:省事.缺点:服务器必须安装Office 这几天做项目 和 大牛学习了一下 新的方法,自己加以总 ...

  9. offsetof的使用

    #include <stddef.h> #define offsetof ( TYPE, m)   (size_t )&reinterpret_cast< const vol ...

  10. Android之layout_alignBottom失效问题

    外面是一层RelativeLayout,前面的text和后面按钮都是设置centerParent_vertical,第二个hello是需要与第一个底部对齐,虽然设置alginBottom指向第一个he ...