林炳文Evankaka原创作品。转载请注明出处http://blog.csdn.net/evankaka
本文工程下载
使用Spring进行基本的JDBC访问数据库有多种选择。Spring至少提供了三种不同的工作模式:Spring JDBC抽象框架core包提供了JDBC模板类,其中JdbcTemplate是core包的核心类,所以其他模板类都是基于它封装完成的,JDBC模板类是第一种工作模式。三种模式如下:
下面主要来讲 JdbcTemplate:
JdbcTemplate类通过模板设计模式帮助我们消除了冗长的代码,只做需要做的事情(即可变部分),并且帮我们做哪些固定部分,如连接的创建及关闭。 JdbcTemplate类对可变部分采用回调接口方式实现,如ConnectionCallback通过回调接口返回给用户一个连接,从而可以使用该连 接做任何事情、StatementCallback通过回调接口返回给用户一个Statement,从而可以使用该Statement做任何事情等等,还 有其他一些回调接口如图所示。
<!-- 配置数据源 --> <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> <!--配置一个JdbcTemplate实例,并将这个“共享的”,“安全的”实例注入到不同的DAO类中去 --> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource" /> </bean>
@Autowired private JdbcTemplate jdbcTemplate;
@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; /** *数据库传输类 *作者 林炳文([email protected] 博客:http://blog.csdn.net/evankaka) *时间 2015.5.24 */ 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; /** *封装数据中的一行 *作者 林炳文([email protected] 博客:http://blog.csdn.net/evankaka) *时间 2015.5.24 */ import java.sql.SQLException; /** * RowMapper可以将数据中的每一行封装成用户定义的类 */ 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; } }
接口类:
package com.mucfc.dao; import java.util.List; import com.mucfc.model.Student; /** *DAO接口类 *作者 林炳文([email protected] 博客:http://blog.csdn.net/evankaka) *时间 2015.5.24 */ public interface StudentDao { /** * 创建数据库表结构 * @param sql */ public void create(); /** * 插入一条学生数据 * @param student */ public void insert(Student student); /** * 通过主键取得对象 * @param id * @return student */ public Student getStudent(Integer id); /** * 取得表中所有的学生 * @param id * @return student */ public List<Student> listStudents(); /** * 通过主键删除对象 * @param id */ public void delete(Integer id); /** * 通过主键更改对象 * @param 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; /** *DAO实现类 *作者 林炳文([email protected] 博客:http://blog.csdn.net/evankaka) *时间 2015.5.24 */ @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() }); } }
新建一个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> <!--配置一个JdbcTemplate实例,并将这个“共享的”,“安全的”实例注入到不同的DAO类中去 --> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 自动扫描注解的bean --> <context:component-scan base-package="com.mucfc.dao" /> </beans>
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(); } }
林炳文Evankaka原创作品。转载请注明出处http://blog.csdn.net/evankaka