Spring与JDBC模板
为了避免直接使用JDBC而带来的复杂且冗长的代码,Spring提供了一个强有力的模板类—JdbcTemplate来简化JDBC操作。并且,数据源DataSource对象与模板JdbcTemplate对象均可通过Bean的形式定义在配置文件中,充分发挥了依赖注入的威力。
jar准备:
Spring 基本 jar
spring-beans-4.2.1.RELEASE.jar
spring-context-4.2.1.RELEASE.jar
spring-core-4.2.1.RELEASE.jar
spring-expression-4.2.1.RELEASE.jar
日志
commons-logging-1.2.jar
log4j-1.2.17.jar
jdbc支持
spring-jdbc-4.2.1.RELEASE.jar
事务支持
spring-tx-4.2.1.RELEASE.jar
Mysql驱动
mysql-connector-java-5.1.7-bin.jar
数据源——c3p0/dbcp
c3p0-0.9.1.2.jar
commons-dbcp2-2.1.1.jar
pool
commons-pool2-2.4.2.jar
所有jar都在这:http://pan.baidu.com/s/1jIxBIa6
创建一个Java Project
创建一个实体类(Student.java):
package com.hk.springdao.beans;
public class Student {
private Integer id;
private String name;
private int age;
public Student() {
super();
}
public Student(String name, int age) {
super();
this.name = name;
this.age = 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 int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
创建数据库表(t_student)
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `t_student`
-- ----------------------------
DROP TABLE IF EXISTS `t_student`;
CREATE TABLE `t_student` (
`t_id` int(5) NOT NULL AUTO_INCREMENT,
`t_age` int(3) DEFAULT NULL,
`t_name` varchar(20) DEFAULT NULL,
PRIMARY KEY (`t_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
业务接口(IStudentService.java)
package com.hk.springdao.service;
import java.util.List;
import com.hk.springdao.beans.Student;
/**
*
* @author 浪丶荡
*
*/
public interface IStudentService {
//增加学生
public void addStudent(Student stu);
//修改学生
public void modifyStudent(Student stu);
//删除学生
public void removeStudent(int stuID);
//查询单个学生
public Student findStuByStuID(int stuID);
//查询所有学生
public List<Student> findAllStudents();
//查询单个学生姓名
public String findStudentNameByID(int stuID);
//查询所有学生姓名
public List<String> findAllStuentNames();
}
dao层接口(IStudentDAO.java)
package com.hk.springdao.dao;
import java.util.List;
import com.hk.springdao.beans.Student;
public interface IStudentDAO {
//增加学生
public void insertStudent(Student stu);
//修改学生
public void updateStudent(Student stu);
//删除学生
public void deleteStudent(int stuID);
//查询学生
public Student selectStuByStuID(int stuID);
public List<Student> selectAllStudents();
public String selectStudentNameByID(int stuID);
public List<String> selectAllStuentNames();
}
dao层接口实现(IStudentDAOImpl.java)
package com.hk.springdao.daoimpl;
import java.util.List;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import com.hk.springdao.beans.Student;
import com.hk.springdao.dao.IStudentDAO;
public class IStudentDAOImpl extends JdbcDaoSupport implements IStudentDAO {
@Override
public void insertStudent(Student stu) {
String sql = "insert into t_student(t_name,t_age) values(?,?)";
this.getJdbcTemplate().update(sql , stu.getName(),stu.getAge());
}
@Override
public void updateStudent(Student stu) {
String sql = "update t_student set t_age= ?,t_name=? where t_id = ?";
this.getJdbcTemplate().update(sql , stu.getAge(),stu.getName(),stu.getId());
}
@Override
public void deleteStudent(int stuID) {
String sql = "delete from t_student where t_id = ?;";
this.getJdbcTemplate().update(sql , stuID);
}
@Override
public Student selectStuByStuID(int stuID) {
String sql = "select * from t_student where t_id = ?";
return null;
}
@Override
public List<Student> selectAllStudents() {
return null;
}
@Override
public String selectStudentNameByID(int stuID) {
return null;
}
@Override
public List<String> selectAllStuentNames() {
return null;
}
}
业务接口实现(StudentServiceImpl.java)
package com.hk.springdao.serviceimpl;
import java.util.List;
import com.hk.springdao.beans.Student;
import com.hk.springdao.dao.IStudentDAO;
import com.hk.springdao.service.IStudentService;
public class StudentServiceImpl implements IStudentService {
private IStudentDAO studentDao;
public void setStudentDao(IStudentDAO studentDao) {
this.studentDao = studentDao;
}
@Override
public void addStudent(Student stu) {
studentDao.insertStudent(stu);
}
@Override
public void modifyStudent(Student stu) {
studentDao.updateStudent(stu);
}
@Override
public void removeStudent(int stuID) {
studentDao.deleteStudent(stuID);
}
@Override
public Student findStuByStuID(int stuID) {
return studentDao.selectStuByStuID(stuID);
}
@Override
public List<Student> findAllStudents() {
return studentDao.selectAllStudents();
}
@Override
public String findStudentNameByID(int stuID) {
return studentDao.selectStudentNameByID(stuID);
}
@Override
public List<String> findAllStuentNames() {
return studentDao.selectAllStuentNames();
}
}
配置文件(applicationContext.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" xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 注册数据源 (Spring内置数据源)-->
<!-- <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name= "driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/test"></property>
<property name="username" value="root"></property>
<property name="password" value="123456"></property>
</bean> -->
<!-- 注册数据源 (DBCP数据源)-->
<!-- <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
<property name= "driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/test"></property>
<property name="username" value="root"></property>
<property name="password" value="123456"></property>
</bean> -->
<!-- 注册数据源 (C3P0数据源)-->
<!-- <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name= "driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3306/test"></property>
<property name="user" value="root"></property>
<property name="password" value="123456"></property>
</bean> -->
<!-- 注册数据源 (C3P0数据源) 从jdbc.properties中获取属性-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name= "driverClass" value="${jdbc.driver}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!-- 注册jdbc属性文件(jdbc.properties) [不常用]-->
<!-- <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:jdbc.properties"></property>
</bean> -->
<!-- 注册jdbc属性文件 方法二需要context约束 -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 注册jdbc模板对象 -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 注册DAO -->
<bean id="dao" class="com.hk.springdao.daoimpl.IStudentDAOImpl">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
<!-- 注册Service -->
<bean id="studentService" class="com.hk.springdao.serviceimpl.StudentServiceImpl">
<property name="studentDao" ref="dao"></property>
</bean>
</beans>
测试
public class MyTest {
@Test
public void testAdd(){
String resouce = "applicationContext.xml";
ApplicationContext ac = new ClassPathXmlApplicationContext(resouce);
IStudentService studentService = (IStudentService) ac.getBean("studentService");
Student stu = new Student("胡浪",18);
studentService.addStudent(stu );
}
}