本文工程下载
一、概述
使用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抽象框架之后,应用开发人员只需要完成斜体字部分的编码工作。)
Spring将替我们完成所有使用JDBC API进行开发的单调乏味的、底层细节处理工作。
二、使用步骤
1、使用JdbcTemplate来访问数据
只需要配置DataSource就能够让JdbcTemplate工作,如下配置:
-
- <bean id="dataSource"
- class="org.springframework.jdbc.datasource.DriverManagerDataSource">
- <property name="driverClassName" value="com.mysql.jdbc.Driver" />
- <property name="url" value="jdbc:mysql://localhost:3306/test" />
- <property name="username" value="root" />
- <property name="password" value="christmas258@" />
- </bean>
-
-
- <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
- <property name="dataSource" ref="dataSource" />
- </bean>
2、现在我们可以把JdbcTemplate装配到DAO,使用它来访问数据库
- @Autowired
- private JdbcTemplate jdbcTemplate;
3、开始操作数据库,如下面的插入
- @Override
- public void insert(Student student) {
- jdbcTemplate.update("INSERT INTO student VALUES('" + student.getId()
- + "', '" + student.getName() + "', '" + student.getAge()
- + "', '" + student.getSex() + "')");
- }
三、使用范例
本文工程下载
这里我们要实例Spring Jdbc和Mysql数据库连接,建表、执行插入、查找、删除等功能。
1、新建一个JavaProject工程,导入包mysql-connector-java-5.1.22-bin.jar+spring3.2+commons-logging-1.2.jar
2、首先先建好数据库对应的Model:
- package com.mucfc.model;
-
-
-
-
-
- public class Student {
- private int id;
- private String name;
- private int age;
- private String sex;
- public Student(){
-
- }
- public Student(int id,String name,int age,String sex){
- this.id=id;
- this.name=name;
- this.age=age;
- this.sex=sex;
- }
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- public String getSex() {
- return sex;
- }
- public void setSex(String sex) {
- this.sex = sex;
- }
-
-
- }
然后还有一个数据库每一行的封装
- package com.mucfc.model;
- import java.sql.ResultSet;
-
-
-
-
-
- import java.sql.SQLException;
-
-
-
- import org.springframework.jdbc.core.RowMapper;
- public class StudentMapper implements RowMapper<Student>{
- public Student mapRow(ResultSet rs, int rowNum) throws SQLException {
- Student student = new Student();
- student.setId(rs.getInt("id"));
- student.setName(rs.getString("name"));
- student.setAge(rs.getInt("age"));
- student.setSex(rs.getString("sex"));
- return student;
- }
- }
3、DAO层:
接口类:
- package com.mucfc.dao;
- import java.util.List;
- import com.mucfc.model.Student;
-
-
-
-
-
- public interface StudentDao {
-
-
-
-
- public void create();
-
-
-
-
- public void insert(Student student);
-
-
-
-
-
- public Student getStudent(Integer id);
-
-
-
-
-
- public List<Student> listStudents();
-
-
-
-
- public void delete(Integer id);
-
-
-
-
- public void update(Student student);
-
- }
实现类:
- package com.mucfc.dao;
-
- import java.util.Iterator;
- import java.util.List;
- import java.util.Map;
-
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.jdbc.core.JdbcTemplate;
- import org.springframework.stereotype.Component;
-
- import com.mucfc.model.Student;
- import com.mucfc.model.StudentMapper;
-
-
-
-
-
- @Component
- public class StudentDaoImpl implements StudentDao {
- @Autowired
- private JdbcTemplate jdbcTemplate;
-
- @Override
- public void create() {
- System.out.println("执行建表操作");
- jdbcTemplate
- .execute("DROP TABLE IF EXISTS student");
- jdbcTemplate
- .execute("CREATE TABLE student (id int primary key, name varchar(100),age int,sex varchar(2))");
- }
-
- @Override
- public void insert(Student student) {
- System.out.println("================执行插入操作================");
- jdbcTemplate.update("INSERT INTO student VALUES('" + student.getId()
- + "', '" + student.getName() + "', '" + student.getAge()
- + "', '" + student.getSex() + "')");
- }
-
- @Override
- public Student getStudent(Integer id) {
- System.out.println("================执行查找单个数据操作================");
- String SQL = "select * from Student where id = ?";
- Student student = jdbcTemplate.queryForObject(SQL,new Object[]{id},new StudentMapper());
- return student;
- }
-
- @Override
- public List<Student> listStudents() {
- System.out.println("================执行查找全部操作================");
- List rows = jdbcTemplate.queryForList("SELECT * FROM student");
- Iterator it = rows.iterator();
- while(it.hasNext()) {
- Map studentMap = (Map) it.next();
- System.out.print("学生id:"+studentMap.get("id") + "; ");
- System.out.print("学生name:"+studentMap.get("name") + "; ");
- System.out.print("学生age:"+studentMap.get("age") + "; ");
- System.out.println("学生sex:"+studentMap.get("sex"));
- }
- return rows;
- }
-
- @Override
- public void delete(Integer id) {
- System.out.println("================执行删除单个数据操作================");
- String SQL = "delete from Student where id = ?";
- jdbcTemplate.update(SQL, id);
- System.out.println("Deleted Record with ID = " + id );
- return;
- }
-
- @Override
- public void update(Student student) {
- System.out.println("================执行更新单个数据操作================");
- jdbcTemplate.update(
- "UPDATE student SET name = ?,age=?,sex=? WHERE id = ?",
- new Object[] { student.getName(), student.getAge(),
- student.getSex(), student.getId() });
-
- }
-
- }
4、Spring配置
新建一个beans.xml,内容如下:
- <?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"
- xmlns:aop="http://www.springframework.org/schema/aop"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
- http://www.springframework.org/schema/aop
- http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.0.xsd">
-
- <bean id="dataSource"
- class="org.springframework.jdbc.datasource.DriverManagerDataSource">
- <property name="driverClassName" value="com.mysql.jdbc.Driver" />
- <property name="url" value="jdbc:mysql://localhost:3306/test" />
- <property name="username" value="root" />
- <property name="password" value="christmas258@" />
- </bean>
-
-
- <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
- <property name="dataSource" ref="dataSource" />
- </bean>
-
-
- <context:component-scan base-package="com.mucfc.dao" />
-
- </beans>
5、测试:
- package com.mucfc.service;
-
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
-
- import com.mucfc.dao.StudentDaoImpl;
- import com.mucfc.model.Student;
-
- public class Test {
-
- public static void main(String[] args) {
- ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
- StudentDaoImpl studentDaoImpl=(StudentDaoImpl)context.getBean("studentDaoImpl");
- studentDaoImpl.create();
- Student student1=new Student(1,"红红",12,"女");
- studentDaoImpl.insert(student1);
- studentDaoImpl.insert(new Student(2,"明明",16,"男"));
- studentDaoImpl.insert(new Student(3,"小王",22,"男"));
- studentDaoImpl.insert(new Student(4,"小刘",15,"男"));
- studentDaoImpl.insert(new Student(5,"张三",23,"男"));
- studentDaoImpl.listStudents();
- System.out.println(studentDaoImpl.getStudent(2));
- studentDaoImpl.update(new Student(2,"大明",15,"男"));
- System.out.println(studentDaoImpl.getStudent(2));
- studentDaoImpl.delete(2);
- studentDaoImpl.listStudents();
- }
-
- }
输出结果: