Sping-Spring JDBC框架
JDBC框架概述
在使用普通的JDBC数据库时,就会很麻烦的写不必要的代码来处理异常,打开和关闭数据库连接等。但Spring JDBC框架负责所有的底层细节,从开始打开连接,准备和执行SQL语句,处理异常,处理事务,都最后的关闭连接。
所以当从数据库中获取数据时,你所要做的就是定义连接参数,指定要执行的SQL语句,每次迭代完成所需的工作。
Spring JDBC提供几种方法和数据库中相应的不同的类与接口。JdbcTemplate类框架是最经典和最受欢迎的方法,也是管理所有数据库通信和异常处理的中央框架类。
JdbcTemplate框架
JdbcTemplate类执行SQL查询,更新语句和存储过程调用,执行迭代结果集合提取返回参数值。它也捕获JDBC异常并转换它们到org.springframework.dao包中定义的通用类,更多的信息,异常层次结构。
JdbcTemplate类的实例是线程安全配置的。所以你可以配置JdbcTemplate的单个实例,然后将这个共享的引用安全的注入到多个DAOs中,使用 JdbcTemplate 类时常见的做法是在你的 Spring 配置文件中配置数据源,然后共享数据源 bean 依赖注入到 DAO 类中,并在数据源的设值函数中创建了 JdbcTemplate。
配置数据源
在数据库springtest中创建一个数据表Student。本文使用MySQL数据库。
DROP DATABASE IF EXISTS springtest; CREATE DATABASE springtest; CREATE TABLE Student( id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, NAME VARCHAR(20) NOT NULL, age INT NOT NULL );
现在,我们需要提供一个数据源到JdbcTemplate中,所以它可以配置本身来获得数据库访问,你可以在XML文件中配置数据源,其中一段代码如下所示:
<bean id="dataSource" class="org.springframework.jdbc.dataSource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"></property> <property name="url" value="jdbc:mysql://10.0.10.33:3306/springtest"></property> <property name="username" value="root"></property> <property name="password" value="123456"></property> </bean>
数据访问对象(DAO)
DAO代表常用的数据库交互的数据库访问对象。DAOs提供一种方法来读取数据并将数据写入数据库中,它们应该通过一个接口显示此功能,应用程序的其余部分访问它们。
在Spring中,数据访问对象(DAO)支持很容易用统一的方法使用数据访问技术,如JDBC,Hibernate,JPA或者JDO。
Spring JDBC示例
创建实体类Student.java
Student.java
package com.fpc.JdbcTemplate; public class Student { private Integer id; private String name; private Integer age; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
创建数据访问对象接口文件StudentDAO.java文件:
StudentDAO.java
package com.fpc.JdbcTemplate.Dao; import javax.sql.DataSource; import com.fpc.JdbcTemplate.Entity.Student; import java.util.List; public interface StudentDao { public void setDataSource(DataSource ds); //CRUD-C public void create(String name,Integer age); //CRUD-R public void getStudent(Integer id); public List<Student> listStudents(); //CRUD-U public void update(Integer id ,String name, Integer age); //CRUD-D public void delete(Integer id); }
创建数据库表与实体类的映射类StudentMapper.java文件
StudentMapper.java
package com.fpc.JdbcTemplate.Mapper; import java.sql.ResultSet; import java.sql.SQLException; import org.springframework.jdbc.core.RowMapper; import com.fpc.JdbcTemplate.Entity.Student; public class StudentMapper implements RowMapper<Student> { @Override public Student mapRow(ResultSet resultSet, int rowNum) throws SQLException { // TODO Auto-generated method stub Student student = new Student(); student.setId(resultSet.getInt("id")); student.setName(resultSet.getString("name")); student.setAge(resultSet.getInt("age")); return student; } }
StudentDao接口的实现类StudentJDBCTemplate.java
StudentJDBCTemplate.java
package com.fpc.JdbcTemplate.DaoImpl; import java.util.List; import javax.sql.DataSource; import org.springframework.jdbc.core.JdbcTemplate; import com.fpc.JdbcTemplate.Dao.StudentDao; import com.fpc.JdbcTemplate.Entity.Student; import com.fpc.JdbcTemplate.Mapper.StudentMapper; public class StudentJDBCTemplate implements StudentDao { private DataSource dataSource; private JdbcTemplate jdbcTemplate; @Override public void setDataSource(DataSource ds) { // TODO Auto-generated method stub dataSource = ds; jdbcTemplate = new JdbcTemple(dataSource); } @Override public void create(String name, Integer age) { // TODO Auto-generated method stub String sql = "insert into Student (name,age) values(?,?)"; jdbcTemplate.update(sql,name,age); } @Override public Student getStudent(Integer id) { // TODO Auto-generated method stub String sql = "select * from Student where id = ?"; Student student = jdbcTemplate.queryForObject(sql, new Object[] {id},new StudentMapper()); return student; } @Override public List<Student> listStudents() { // TODO Auto-generated method stub String sql = "select * from Student"; List<Student> students = jdbcTemplate.query(sql,new StudentMapper()); return students; } @Override public void update(Integer id, String name, Integer age) { // TODO Auto-generated method stub String sql = "update Student set name = ? ,age = ? where id = ?"; jdbcTemplate.update(sql,name,age,id); } @Override public void delete(Integer id) { // TODO Auto-generated method stub String sql = "delete from Student where id = ?"; jdbcTemplate.update(sql,id); } }
编写测试类StudentJDBCTemplateTest.java
package com.fpc.JdbcTemplate.Test; import java.util.List; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.fpc.JdbcTemplate.DaoImpl.StudentJDBCTemplate; import com.fpc.JdbcTemplate.Entity.Student; public class StudentJDBCTemplateTest { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml"); StudentJDBCTemplate studentJDBCTemplate = (StudentJDBCTemplate) context.getBean("studentJDBCTemplate"); //测试create功能 studentJDBCTemplate.create("fpc", 23); } }
Bean.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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://10.0.10.33:3306/springtest"/> <property name="username" value="root"/> <property name="password" value="123456"/> </bean> <!-- Definition for studentJDBCTemplate bean --> <bean id="studentJDBCTemplate" class="com.fpc.JdbcTemplate.DaoImpl.StudentJDBCTemplate"> <property name="dataSource" ref="dataSource" /> </bean> </beans>
测试插入功能:
//测试create功能 studentJDBCTemplate.create("fpc", 23);
查看数据库中的结果:
测试getStudent功能
//测试getStudent功能 Student student = studentJDBCTemplate.getStudent(1); System.out.println("student'id : " + student.getId() + " student'name : " + student.getName() + " student'age : " + student.getAge());
运行结果:
测试update功能:
//测试update功能 System.out.println("before update: "); Student student = studentJDBCTemplate.getStudent(1); System.out.println("student'id : " + student.getId() + " student'name : " + student.getName() + " student'age : " + student.getAge()); System.out.println("after update: "); studentJDBCTemplate.update(1, "fpc", 24); Student student1 = studentJDBCTemplate.getStudent(1); System.out.println("student'id : " + student1.getId() + " student'name : " + student1.getName() + " student'age : " + student1.getAge());
测试listStudents功能:
//测试listStudent功能 studentJDBCTemplate.create("Lily", 25); List<Student> list = studentJDBCTemplate.listStudents(); for (Student student : list ) { System.out.println("student'id : " + student.getId() + " student'name : " + student.getName() + " student'age : " + student.getAge()); }
测试delete功能:
//测试delete功能 System.out.println("before delete: "); List<Student> list1 = studentJDBCTemplate.listStudents(); for (Student student : list1 ) { System.out.println("student'id : " + student.getId() + " student'name : " + student.getName() + " student'age : " + student.getAge()); } studentJDBCTemplate.delete(1); System.out.println("after delete: "); List<Student> list = studentJDBCTemplate.listStudents(); for (Student student : list ) { System.out.println("student'id : " + student.getId() + " student'name : " + student.getName() + " student'age : " + student.getAge()); }
运行结果: