Spring JDBC原理与应用实例讲解

本文工程下载

一、概述

使用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做任何事情等等,还 有其他一些回调接口如图所示。

 

JdbcTemplate支持的回调接口

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

 

  • 定义数据库连接参数
  • 打开数据库连接
  • 声明SQL语句
  • 预编译并执行SQL语句
  • 遍历查询结果(如果需要的话)
  • 处理每一次遍历操作
  • 处理抛出的任何异常
  • 处理事务
  • 关闭数据库连接

Spring将替我们完成所有使用JDBC API进行开发的单调乏味的、底层细节处理工作。 

 

二、使用步骤

1、使用JdbcTemplate来访问数据

    只需要配置DataSource就能够让JdbcTemplate工作,如下配置:

 

 

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  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="christmas258@" />  
  8. </bean>  
  9.   
  10. <!--配置一个JdbcTemplate实例,并将这个“共享的”,“安全的”实例注入到不同的DAO类中去 -->  
  11. <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">  
  12.     <property name="dataSource" ref="dataSource" />  
  13. </bean>  


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

 

 

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. @Autowired  
  2. private JdbcTemplate jdbcTemplate;  


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

 

 

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  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:

 

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  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.     }  
  15.     public Student(int id,String name,int age,String sex){  
  16.         this.id=id;  
  17.         this.name=name;  
  18.         this.age=age;  
  19.         this.sex=sex;  
  20.     }  
  21.     public int getId() {  
  22.         return id;  
  23.     }  
  24.     public void setId(int id) {  
  25.         this.id = id;  
  26.     }  
  27.     public String getName() {  
  28.         return name;  
  29.     }  
  30.     public void setName(String name) {  
  31.         this.name = name;  
  32.     }  
  33.     public int getAge() {  
  34.         return age;  
  35.     }  
  36.     public void setAge(int age) {  
  37.         this.age = age;  
  38.     }  
  39.     public String getSex() {  
  40.         return sex;  
  41.     }  
  42.     public void setSex(String sex) {  
  43.         this.sex = sex;  
  44.     }  
  45.   
  46.   
  47. }  

然后还有一个数据库每一行的封装

 

 

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  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层:

 

接口类:

 

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  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.   
  43. }  

实现类:

 

 

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


4、Spring配置

 

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

 

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  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="christmas258@" />  
  19.     </bean>  
  20.   
  21.     <!--配置一个JdbcTemplate实例,并将这个“共享的”,“安全的”实例注入到不同的DAO类中去 -->  
  22.     <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">  
  23.         <property name="dataSource" ref="dataSource" />  
  24.     </bean>  
  25.   
  26.     <!-- 自动扫描注解的bean -->  
  27.     <context:component-scan base-package="com.mucfc.dao" />  
  28.   
  29. </beans>  


5、测试:

 

 

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
 
  1. package com.mucfc.service;  
  2.   
  3. import org.springframework.context.ApplicationContext;  
  4. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  5.   
  6. import com.mucfc.dao.StudentDaoImpl;  
  7. import com.mucfc.model.Student;  
  8.   
  9. public class Test {  
  10.   
  11.     public static void main(String[] args) {  
  12.          ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");  
  13.          StudentDaoImpl studentDaoImpl=(StudentDaoImpl)context.getBean("studentDaoImpl");  
  14.          studentDaoImpl.create();  
  15.          Student student1=new Student(1,"红红",12,"女");  
  16.          studentDaoImpl.insert(student1);  
  17.          studentDaoImpl.insert(new Student(2,"明明",16,"男"));  
  18.          studentDaoImpl.insert(new Student(3,"小王",22,"男"));  
  19.          studentDaoImpl.insert(new Student(4,"小刘",15,"男"));  
  20.          studentDaoImpl.insert(new Student(5,"张三",23,"男"));    
  21.          studentDaoImpl.listStudents();  
  22.         System.out.println(studentDaoImpl.getStudent(2));   
  23.         studentDaoImpl.update(new Student(2,"大明",15,"男"));  
  24.         System.out.println(studentDaoImpl.getStudent(2));   
  25.         studentDaoImpl.delete(2);  
  26.          studentDaoImpl.listStudents();  
  27.     }  
  28.   
  29. }  


输出结果:

 

猜你喜欢

转载自harborchung.iteye.com/blog/2229704