1.引出SpringJDBC的概念
在学习JDBC编程时我们会感觉到JDBC的操作是多么繁琐,那么当我们学习的Hibernate框架时,我们感觉到数据库的操作也变非常简单,提高了开发效率。但是当使用Hibernate不能满足性能或者灵活性要求必须使用Sql操作时,那么我们只能是纯JDBC来开发,为了解决这一问题,那么Spring也给出了相应的解决方案,我们可以使用Spring JDBC 框架方便简单的完成JDBC操作,只需要声明Sql语句,调用适合的Spring JDBC框架中的APL,来处理结果集。
2.Spring JDBC的组成
SpringJDBC框架的4个组成部分:
3.使用Spring jdbcTemplate实现数据库操作步骤
3.1引入jar包:
3.2搭建架构(dao,entity,service)
entity:
package cn.entity;
/**
* 学生实体类
*
* @author hyj
*
*/
public class Student {
// 学生id
private Integer id;
// 学生姓名
private String name;
// 学生年龄
private Integer age;
public Student() {
super();
// TODO Auto-generated constructor stub
}
public Student(Integer id, String name, Integer age) {
super();
this.id = id;
this.name = name;
this.age = age;
}
public Student(Integer id, String name) {
super();
this.id = id;
this.name = name;
}
public Student(String name, Integer 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 Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
dao:
package cn.dao;
import java.util.List;
import cn.entity.Student;
public interface StudentDao {
/**
* 查询全部
* @return
*/
public List<Student> findAll();
/**
* 添加
* @param student
*/
public void add(Student student);
/**
* 删除
* @param id
*/
public void delete(Integer id);
/**
* 更新
* @param student
*/
public void update(Student student);
/**
* 查询总记录数
* @return
*/
public Integer count();
/**
* 调用存储过程实现根据学生id查询学生姓名
* @param id
* @return
*/
public String byIdSelectName(Integer id);
/**
* 查询所有信息:利用query(String sql,RowMapper rowMapper)
* @return
*/
public List<Student> select();
/**
* 根据id查询Student对象
* @return
*/
public Student byIdStudent(Integer id);
}
daoImpl:
package cn.dao.impl;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.CallableStatementCallback;
import org.springframework.jdbc.core.CallableStatementCreator;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import cn.dao.StudentDao;
import cn.entity.Student;
import cn.util.MyRowMapper;
public class StudentDaoImpl implements StudentDao {
private JdbcTemplate jdbcTemplate;
/**
* 查询所有的信息
*/
@Override
public List<Student> findAll() {
List<Student> studentsList = new ArrayList<Student>();
// 查询的sql语句
String sql = "select * from student";
// 调用方法获取集合数据
List stuList = jdbcTemplate.queryForList(sql);
// 遍历集合,每一个student代表一个Student实体
Iterator iterator = stuList.iterator();
while (iterator.hasNext()) {
Map map = (Map) iterator.next();
Student stu = new Student();
stu.setName((String) map.get("name"));
stu.setId(((BigDecimal) map.get("id")).intValue());
stu.setAge(((BigDecimal) map.get("age")).intValue());
studentsList.add(stu);
}
return studentsList;
}
/**
* 添加的方法
*/
@Override
public void add(Student student) {
// 1.提供一个可以添加的sql语句
String sql = "insert into student values(?,?,?)";
// 2.提供参数
Object[] args = new Object[] { student.getId(), student.getName(),
student.getAge() };
// 3.调用jdbcTemplate的update方法进行添加操作
jdbcTemplate.update(sql, args);
}
/**
* 删除
*/
@Override
public void delete(Integer id) {
String sql = "delete from student where id=?";
// 该方法返回的值是int类型代表受影响行数
jdbcTemplate.update(sql, id);
}
/**
* 更新的方法
*/
@Override
public void update(Student student) {
String sql = "update student set name=? where id=?";
Object[] args = new Object[] { student.getName(), student.getId() };
jdbcTemplate.update(sql, args);
}
/**
*
* 查询总记录数
*/
@Override
public Integer count() {
String sql = "select count(1) from student";
Object count = jdbcTemplate.queryForObject(sql, Object.class);
return ((BigDecimal) count).intValue();
}
/**
* 调用存储过程实现根据学生id查询学生姓名
*
* @param id
* @return
*/
@SuppressWarnings("unchecked")
@Override
public String byIdSelectName(Integer id) {
String sql = "select name from student where id=?";
Object[] args = new Object[] { id };
String name = jdbcTemplate.queryForObject(sql, args,
java.lang.String.class);
return name;
}
/**
* 查询所有信息:利用query(String sql,RowMapper rowMapper)
*
* @return
*/
@Override
public List<Student> select() {
String sql = "select * from student";
List<Student> list = jdbcTemplate.query(sql, new MyRowMapper());
return list;
}
/**
* 根据id查询单个对象
*/
@Override
public Student byIdStudent(Integer id) {
String sql = "select * from student where id=?";
Student student = jdbcTemplate.queryForObject(sql,
new BeanPropertyRowMapper<Student>(Student.class), id);
return student;
}
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
}
service :
package cn.service;
import java.util.List;
import cn.entity.Student;
public interface StudentService {
/**
* 查询全部
* @return
*/
public List<Student> findAll();
/**
* 添加
* @param student
*/
public void add(Student student);
/**
* 删除
* @param id
*/
public void delete(Integer id);
/**
* 更新
* @param student
*/
public void update(Student student);
/**
* 查询总记录数
* @return
*/
public Integer count();
/**
* 调用存储过程实现根据学生id查询学生姓名
* @param id
* @return
*/
public String byIdSelectName( final Integer id);
/**
* 查询所有信息:利用query(String sql,RowMapper rowMapper)
* @return
*/
public List<Student> select();
/**
* 根据id查询Student对象
* @return
*/
public Student byIdStudent(Integer id);
}
service:
package cn.service;
import java.util.List;
import cn.entity.Student;
public interface StudentService {
/**
* 查询全部
* @return
*/
public List<Student> findAll();
/**
* 添加
* @param student
*/
public void add(Student student);
/**
* 删除
* @param id
*/
public void delete(Integer id);
/**
* 更新
* @param student
*/
public void update(Student student);
/**
* 查询总记录数
* @return
*/
public Integer count();
/**
*
* @param id
* @return
*/
public String byIdSelectName(Integer id);
/**
* 查询所有信息:利用query(String sql,RowMapper rowMapper)
* @return
*/
public List<Student> select();
/**
* 根据id查询Student对象
* @return
*/
public Student byIdStudent(Integer id);
}
serviceImpl
package cn.service.impl;
import java.util.List;
import cn.dao.StudentDao;
import cn.entity.Student;
import cn.service.StudentService;
public class StudentServiceImpl implements StudentService {
private StudentDao stuDao;
@Override
public List<Student> findAll() {
// TODO Auto-generated method stub
return stuDao.findAll();
}
@Override
public void add(Student student) {
stuDao.add(student);
}
@Override
public void delete(Integer id) {
stuDao.delete(id);
}
@Override
public void update(Student update) {
stuDao.update(update);
}
public StudentDao getStuDao() {
return stuDao;
}
public void setStuDao(StudentDao stuDao) {
this.stuDao = stuDao;
}
@Override
public Integer count() {
return stuDao.count();
}
@Override
public String byIdSelectName( Integer id) {
return stuDao.byIdSelectName(id);
}
@Override
public List<Student> select() {
return stuDao.select();
}
@Override
public Student byIdStudent(Integer id) {
// TODO Auto-generated method stub
return stuDao.byIdStudent(id);
}
}
util:
package cn.util;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
import cn.entity.Student;
public class MyRowMapper implements RowMapper<Student>{
@Override
public Student mapRow(ResultSet rs, int rowNum) throws SQLException {
Student student=new Student();
student.setAge(rs.getInt("age"));
student.setId(rs.getInt("id"));
student.setName(rs.getString("name"));
return student;
}
}
3.3配置文件: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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 1.配置普通数据源 -->
<!-- <bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
指定jdbc驱动
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
连接数据库的url地址
<property name="url" value="jdbc:mysql://localhost:3306/Success"></property>
连接数据的用户名和密码
<property name="username" value="root"></property>
<property name="password" value="123"></property>
</bean> -->
<!-- 2.c3p0 数据源-->
<bean id="dataSource"
class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!-- 指定jdbc驱动 -->
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<!-- 连接数据库的url地址 -->
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/Success"></property>
<!-- 连接数据的用户名和密码 -->
<property name="user" value="root"></property>
<property name="password" value="123"></property>
</bean>
<!-- 2配置jdbcTemplate -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 定义dao的实现 -->
<bean id="stuDaoimpl" class="cn.dao.impl.StudentDaoImpl">
<!-- 给jdbcTemplate植入引用 -->
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
<!-- 定义Service实现 -->
<bean id="stuserviceimpl" class="cn.service.impl.StudentServiceImpl">
<!-- 给stuDao植入引用 -->
<property name="stuDao" ref="stuDaoimpl"></property>
</bean>
</beans>
3.4测试类
package cn.test;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.entity.Student;
import cn.service.StudentService;
public class TestHappy {
private StudentService stuService;
@Before
public void before(){
ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
stuService =(StudentService)context.getBean("stuserviceimpl");
}
/**
* 测试添加
*/
@Test
public void add(){
stuService.add(new Student(4,"张三4",21));
System.out.println("add success.............");
}
/**
* 更新方法测试
*/
@Test
public void update(){
stuService.update(new Student(002,"张三2"));
System.out.println("update success.........");
}
/**
* 删除方法测试
*/
@Test
public void delete(){
stuService.delete(001);
System.out.println("delete success.........");
}
/**
*查询方法测试
*/
@Test
public void findAll(){
List<Student> stuList= stuService.findAll();
for (Student student : stuList) {
System.out.println("学生编号:"+student.getId()+"\t学生姓名:"+student.getName()+"\t学生年龄:"+student.getAge());
}
}
/**
* 查询学生总记录数
*/
@Test
public void count(){
Integer result= stuService.count();
System.out.println("学生总数:"+result);
}
/**
* 调用存储过程实现根据学生id查询学生姓名
* @param id
* @return
*/
@Test
public void byIdSelectName(){
String name=stuService.byIdSelectName(2);
System.out.println("学生姓名:"+name);
}
/**
* 查询所有信息:利用query(String sql,RowMapper rowMapper)
* @return
*/
@Test
public void select(){
List<Student> list=stuService.select();
for (Student item : list) {
System.out.println("学生姓名:"+item.getName());
}
}
/**
* 根据id查询查询单个对象
* @return
*/
@Test
public void byIdStudent(){
Student student=stuService.byIdStudent(2);
System.out.println(student.getName());
System.out.println(student.getAge());
}
}