林炳文Evankaka原创作品。转自https://blog.csdn.net/Evankaka/article/details/45477185

本文工程下载

一、概述

使用Spring进行基本的JDBC访问数据库有多种选择。Spring至少提供了三种不同的工作模式:Spring JDBC抽象框架core包提供了JDBC模板类,其中JdbcTemplate是core包的核心类,所以其他模板类都是基于它封装完成的,JDBC模板类是第一种工作模式。三种模式如下:

  • JdbcTemplate:是Spring中最基本的JDBC模板, 利用JDBC和简单的索引参数查询对数据库进行简单访问
  • NamedParameterJdbcTemplate:能够在查询的时候把值绑定到SQL里的命名参数,而不是索引参数   NamedParameterJdbcTemplate内部包含了一个JdbcTemplate,所以JdbcTemplate能做的事情NamedParameterJdbcTemplate都能干    NamedParameterJdbcTemplate相对于JdbcTemplate主要增加了参数可以命名的功能。
  •  SimpleJdbcTemplate:利用Java5的特性,比如自动装箱、通用和可变参数列表来简化JDBC模板的使用SimpleJdbcTemplate内部包含了一个NamedParameterJdbcTemplate;所以NamedParameterJdbcTemplate能做的事情SimpleJdbcTemplate都能干,SimpleJdbcTemplate相对于NamedParameterJdbcTemplate主要增加了JDK5.0的泛型和可变长度参数支持。

      下面主要来讲 JdbcTemplate:

       JdbcTemplate类通过模板设计模式帮助我们消除了冗长的代码,只做需要做的事情(即可变部分),并且帮我们做哪些固定部分,如连接的创建及关闭。 JdbcTemplate类对可变部分采用回调接口方式实现,如ConnectionCallback通过回调接口返回给用户一个连接,从而可以使用该连 接做任何事情、StatementCallback通过回调接口返回给用户一个Statement,从而可以使用该Statement做任何事情等等,还 有其他一些回调接口如图所示。

Spring JDBC原理与应用实例讲解

JdbcTemplate支持的回调接口

Spring JDBC抽象框架所带来的价值将在以下几个方面得以体现:(注:使用了Spring JDBC抽象框架之后,应用开发人员只需要完成斜体字部分的编码工作。)

  • 定义数据库连接参数
  • 打开数据库连接
  • 声明SQL语句
  • 预编译并执行SQL语句
  • 遍历查询结果(如果需要的话)
  • 处理每一次遍历操作
  • 处理抛出的任何异常
  • 处理事务
  • 关闭数据库连接
Spring将替我们完成所有使用JDBC API进行开发的单调乏味的、底层细节处理工作。

二、使用步骤

1、使用JdbcTemplate来访问数据
    只需要配置DataSource就能够让JdbcTemplate工作,如下配置:

  1. <!-- 配置数据源 -->
  2. <bean id="dataSource"
  3. class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  4. <property name="driverClassName" value="com.mysql.jdbc.Driver" />
  5. <property name="url" value="jdbc:mysql://localhost:3306/test" />
  6. <property name="username" value="root" />
  7. <property name="password" value="[email protected]" />
  8. </bean>
  9. <!--配置一个JdbcTemplate实例,并将这个“共享的”,“安全的”实例注入到不同的DAO类中去 -->
  10. <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
  11. <property name="dataSource" ref="dataSource" />
  12. </bean>

2、现在我们可以把JdbcTemplate装配到DAO,使用它来访问数据库

  1. @Autowired
  2. private JdbcTemplate jdbcTemplate;

3、开始操作数据库,如下面的插入

  1. @Override
  2. public void insert(Student student) {
  3. jdbcTemplate.update("INSERT INTO student VALUES('" + student.getId()
  4. + "', '" + student.getName() + "', '" + student.getAge()
  5. + "', '" + student.getSex() + "')");
  6. }

三、使用范例

本文工程下载

这里我们要实例Spring Jdbc和Mysql数据库连接,建表、执行插入、查找、删除等功能。

1、新建一个JavaProject工程,导入包mysql-connector-java-5.1.22-bin.jar+spring3.2+commons-logging-1.2.jar

2、首先先建好数据库对应的Model:

  1. package com.mucfc.model;
  2. /**
  3. *数据库传输类
  4. *作者 林炳文([email protected] 博客:http://blog.csdn.net/evankaka)
  5. *时间 2015.5.24
  6. */
  7. public class Student {
  8. private int id;
  9. private String name;
  10. private int age;
  11. private String sex;
  12. public Student(){
  13. }
  14. public Student(int id,String name,int age,String sex){
  15. this.id=id;
  16. this.name=name;
  17. this.age=age;
  18. this.sex=sex;
  19. }
  20. public int getId() {
  21. return id;
  22. }
  23. public void setId(int id) {
  24. this.id = id;
  25. }
  26. public String getName() {
  27. return name;
  28. }
  29. public void setName(String name) {
  30. this.name = name;
  31. }
  32. public int getAge() {
  33. return age;
  34. }
  35. public void setAge(int age) {
  36. this.age = age;
  37. }
  38. public String getSex() {
  39. return sex;
  40. }
  41. public void setSex(String sex) {
  42. this.sex = sex;
  43. }
  44. }
然后还有一个数据库每一行的封装

  1. package com.mucfc.model;
  2. import java.sql.ResultSet;
  3. /**
  4. *封装数据中的一行
  5. *作者 林炳文([email protected] 博客:http://blog.csdn.net/evankaka)
  6. *时间 2015.5.24
  7. */
  8. import java.sql.SQLException;
  9. /**
  10. * RowMapper可以将数据中的每一行封装成用户定义的类
  11. */
  12. import org.springframework.jdbc.core.RowMapper;
  13. public class StudentMapper implements RowMapper<Student>{
  14. public Student mapRow(ResultSet rs, int rowNum) throws SQLException {
  15. Student student = new Student();
  16. student.setId(rs.getInt("id"));
  17. student.setName(rs.getString("name"));
  18. student.setAge(rs.getInt("age"));
  19. student.setSex(rs.getString("sex"));
  20. return student;
  21. }
  22. }

3、DAO层:

接口类:

  1. package com.mucfc.dao;
  2. import java.util.List;
  3. import com.mucfc.model.Student;
  4. /**
  5. *DAO接口类
  6. *作者 林炳文([email protected] 博客:http://blog.csdn.net/evankaka)
  7. *时间 2015.5.24
  8. */
  9. public interface StudentDao {
  10. /**
  11. * 创建数据库表结构
  12. * @param sql
  13. */
  14. public void create();
  15. /**
  16. * 插入一条学生数据
  17. * @param student
  18. */
  19. public void insert(Student student);
  20. /**
  21. * 通过主键取得对象
  22. * @param id
  23. * @return student
  24. */
  25. public Student getStudent(Integer id);
  26. /**
  27. * 取得表中所有的学生
  28. * @param id
  29. * @return student
  30. */
  31. public List<Student> listStudents();
  32. /**
  33. * 通过主键删除对象
  34. * @param id
  35. */
  36. public void delete(Integer id);
  37. /**
  38. * 通过主键更改对象
  39. * @param id
  40. */
  41. public void update(Student student);
  42. }
实现类:

  1. package com.mucfc.dao;
  2. import java.util.Iterator;
  3. import java.util.List;
  4. import java.util.Map;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.jdbc.core.JdbcTemplate;
  7. import org.springframework.stereotype.Component;
  8. import com.mucfc.model.Student;
  9. import com.mucfc.model.StudentMapper;
  10. /**
  11. *DAO实现类
  12. *作者 林炳文([email protected] 博客:http://blog.csdn.net/evankaka)
  13. *时间 2015.5.24
  14. */
  15. @Component
  16. public class StudentDaoImpl implements StudentDao {
  17. @Autowired
  18. private JdbcTemplate jdbcTemplate;
  19. @Override
  20. public void create() {
  21. System.out.println("执行建表操作");
  22. jdbcTemplate
  23. .execute("DROP TABLE IF EXISTS student");
  24. jdbcTemplate
  25. .execute("CREATE TABLE student (id int primary key, name varchar(100),age int,sex varchar(2))");
  26. }
  27. @Override
  28. public void insert(Student student) {
  29. System.out.println("================执行插入操作================");
  30. jdbcTemplate.update("INSERT INTO student VALUES('" + student.getId()
  31. + "', '" + student.getName() + "', '" + student.getAge()
  32. + "', '" + student.getSex() + "')");
  33. }
  34. @Override
  35. public Student getStudent(Integer id) {
  36. System.out.println("================执行查找单个数据操作================");
  37. String SQL = "select * from Student where id = ?";
  38. Student student = jdbcTemplate.queryForObject(SQL,new Object[]{id},new StudentMapper());
  39. return student;
  40. }
  41. @Override
  42. public List<Student> listStudents() {
  43. System.out.println("================执行查找全部操作================");
  44. List rows = jdbcTemplate.queryForList("SELECT * FROM student");
  45. Iterator it = rows.iterator();
  46. while(it.hasNext()) {
  47. Map studentMap = (Map) it.next();
  48. System.out.print("学生id:"+studentMap.get("id") + "; ");
  49. System.out.print("学生name:"+studentMap.get("name") + "; ");
  50. System.out.print("学生age:"+studentMap.get("age") + "; ");
  51. System.out.println("学生sex:"+studentMap.get("sex"));
  52. }
  53. return rows;
  54. }
  55. @Override
  56. public void delete(Integer id) {
  57. System.out.println("================执行删除单个数据操作================");
  58. String SQL = "delete from Student where id = ?";
  59. jdbcTemplate.update(SQL, id);
  60. System.out.println("Deleted Record with ID = " + id );
  61. return;
  62. }
  63. @Override
  64. public void update(Student student) {
  65. System.out.println("================执行更新单个数据操作================");
  66. jdbcTemplate.update(
  67. "UPDATE student SET name = ?,age=?,sex=? WHERE id = ?",
  68. new Object[] { student.getName(), student.getAge(),
  69. student.getSex(), student.getId() });
  70. }
  71. }

4、Spring配置

新建一个beans.xml,内容如下:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
  4. xmlns:aop="http://www.springframework.org/schema/aop"
  5. xsi:schemaLocation="
  6. http://www.springframework.org/schema/beans
  7. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  8. http://www.springframework.org/schema/aop
  9. http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
  10. http://www.springframework.org/schema/context
  11. http://www.springframework.org/schema/context/spring-context-3.0.xsd">
  12. <!-- 配置数据源 -->
  13. <bean id="dataSource"
  14. class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  15. <property name="driverClassName" value="com.mysql.jdbc.Driver" />
  16. <property name="url" value="jdbc:mysql://localhost:3306/test" />
  17. <property name="username" value="root" />
  18. <property name="password" value="[email protected]" />
  19. </bean>
  20. <!--配置一个JdbcTemplate实例,并将这个“共享的”,“安全的”实例注入到不同的DAO类中去 -->
  21. <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
  22. <property name="dataSource" ref="dataSource" />
  23. </bean>
  24. <!-- 自动扫描注解的bean -->
  25. <context:component-scan base-package="com.mucfc.dao" />
  26. </beans>

5、测试:

  1. package com.mucfc.service;
  2. import org.springframework.context.ApplicationContext;
  3. import org.springframework.context.support.ClassPathXmlApplicationContext;
  4. import com.mucfc.dao.StudentDaoImpl;
  5. import com.mucfc.model.Student;
  6. public class Test {
  7. public static void main(String[] args) {
  8. ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
  9. StudentDaoImpl studentDaoImpl=(StudentDaoImpl)context.getBean("studentDaoImpl");
  10. studentDaoImpl.create();
  11. Student student1=new Student(1,"红红",12,"女");
  12. studentDaoImpl.insert(student1);
  13. studentDaoImpl.insert(new Student(2,"明明",16,"男"));
  14. studentDaoImpl.insert(new Student(3,"小王",22,"男"));
  15. studentDaoImpl.insert(new Student(4,"小刘",15,"男"));
  16. studentDaoImpl.insert(new Student(5,"张三",23,"男"));
  17. studentDaoImpl.listStudents();
  18. System.out.println(studentDaoImpl.getStudent(2));
  19. studentDaoImpl.update(new Student(2,"大明",15,"男"));
  20. System.out.println(studentDaoImpl.getStudent(2));
  21. studentDaoImpl.delete(2);
  22. studentDaoImpl.listStudents();
  23. }
  24. }

输出结果:

Spring JDBC原理与应用实例讲解





相关文章: