第一节:

工程结构:

1)student.java:

package com.cy.model;

public class Student {
private int id;
private String name;
private int age; public Student() {
super();
// TODO Auto-generated constructor stub
} public Student(String name, int age) {
super();
this.name = name;
this.age = age;
} public Student(int id, String name, int age) {
super();
this.id = id;
this.name = name;
this.age = age;
} 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;
} @Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";
} }

2)StudentDao.java/StudentDaoImpl.java:

package com.cy.dao;

import java.util.List;

import com.cy.model.Student;

public interface StudentDao {
public int addStudent(Student student); public int updateStudent(Student student); public int deleteStudent(int id); public List<Student> findStudents();
}
package com.cy.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List; import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler; import com.cy.dao.StudentDao;
import com.cy.model.Student; public class StudentDaoImpl implements StudentDao { private JdbcTemplate jdbcTemplate; public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
} @Override
public int addStudent(Student student) {
String sql = "insert into t_student values (null, ?, ?)";
Object params[] = new Object[]{student.getName(), student.getAge()};
return jdbcTemplate.update(sql, params);
} @Override
public int updateStudent(Student student) {
String sql = "update t_student set name=?, age=? where id = ?";
Object params[] = new Object[]{student.getName(), student.getAge(), student.getId()};
return jdbcTemplate.update(sql, params);
} @Override
public int deleteStudent(int id) {
String sql = "delete from t_student where id = ?";
Object params[] = new Object[]{id};
return jdbcTemplate.update(sql, params);
} /**
* 查询所有的学生
*/
@Override
public List<Student> findStudents() {
String sql = "select * from t_student";
final List<Student> studentList = new ArrayList<Student>();
jdbcTemplate.query(sql, new RowCallbackHandler(){ @Override
public void processRow(ResultSet rs) throws SQLException {
Student student = new Student();
student.setId(rs.getInt("id"));
student.setName(rs.getString("name"));
student.setAge(rs.getInt("age"));
studentList.add(student);
} });
return studentList;
} }

3)StudentService.java/StudentServiceImpl.java:

package com.cy.service;

import java.util.List;

import com.cy.model.Student;

public interface StudentService {

    public int addStudent(Student student);

    public int updateStudent(Student student);

    public int deleteStudent(int id);

    public List<Student> findStudents();
}
package com.cy.service.impl;

import java.util.List;

import com.cy.dao.StudentDao;
import com.cy.model.Student;
import com.cy.service.StudentService; public class StudentServiceImpl implements StudentService{ private StudentDao studentDao; public void setStudentDao(StudentDao studentDao) {
this.studentDao = studentDao;
} @Override
public int addStudent(Student student) {
return studentDao.addStudent(student);
} @Override
public int updateStudent(Student student) {
return studentDao.updateStudent(student);
} @Override
public int deleteStudent(int id) {
return studentDao.deleteStudent(id);
} @Override
public List<Student> findStudents() {
return studentDao.findStudents();
} }

4)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:aop="http://www.springframework.org/schema/aop"
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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean> <context:property-placeholder location="jdbc.properties"/> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean> <bean id="studentDao" class="com.cy.dao.impl.StudentDaoImpl">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean> <bean id="studentService" class="com.cy.service.impl.StudentServiceImpl">
<property name="studentDao" ref="studentDao"></property>
</bean> </beans>

5)jdbc.properties:

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db_spring
jdbc.username=root
jdbc.password=root

6)测试代码:

package com.cy.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 com.cy.model.Student;
import com.cy.service.StudentService; public class T {
private ApplicationContext ac; @Before
public void setUp() throws Exception {
ac=new ClassPathXmlApplicationContext("beans.xml");
} @Test
public void addStudent() {
StudentService studentService=(StudentService)ac.getBean("studentService");
int addNums=studentService.addStudent(new Student("晶", 1));
if(addNums==1){
System.out.println("添加成功");
}
} @Test
public void updateStudent() {
StudentService studentService=(StudentService)ac.getBean("studentService");
int updateNums=studentService.updateStudent(new Student(4, "杨静", 10));
if(updateNums==1){
System.out.println("修改成功");
}
} @Test
public void deleteStudent() {
StudentService studentService=(StudentService)ac.getBean("studentService");
int deleteNums = studentService.deleteStudent(4);
if(deleteNums==1){
System.out.println("删除成功!");
}
} @Test
public void findStudents() {
StudentService studentService=(StudentService)ac.getBean("studentService");
List<Student> studentList = studentService.findStudents();
for(Student student : studentList){
System.out.println(student);
}
}
}

查询所有学生findStudents方法console打印:

第二节:

1.通过继承JdbcDaoSupport,我们原来的JdbcTemplate就不用写了:

根据上面项目的代码,做些修改:

1)StudentDaoImpl.java:

package com.cy.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List; import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.core.support.JdbcDaoSupport; import com.cy.dao.StudentDao;
import com.cy.model.Student; public class StudentDaoImpl extends JdbcDaoSupport implements StudentDao { @Override
public int addStudent(Student student) {
String sql = "insert into t_student values (null, ?, ?)";
Object params[] = new Object[]{student.getName(), student.getAge()};
return this.getJdbcTemplate().update(sql, params);
} @Override
public int updateStudent(Student student) {
String sql = "update t_student set name=?, age=? where id = ?";
Object params[] = new Object[]{student.getName(), student.getAge(), student.getId()};
return this.getJdbcTemplate().update(sql, params);
} @Override
public int deleteStudent(int id) {
String sql = "delete from t_student where id = ?";
Object params[] = new Object[]{id};
return this.getJdbcTemplate().update(sql, params);
} /**
* 查询所有的学生
*/
@Override
public List<Student> findStudents() {
String sql = "select * from t_student";
final List<Student> studentList = new ArrayList<Student>();
this.getJdbcTemplate().query(sql, new RowCallbackHandler(){ @Override
public void processRow(ResultSet rs) throws SQLException {
Student student = new Student();
student.setId(rs.getInt("id"));
student.setName(rs.getString("name"));
student.setAge(rs.getInt("age"));
studentList.add(student);
} });
return studentList;
} }

2)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:aop="http://www.springframework.org/schema/aop"
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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean> <context:property-placeholder location="jdbc.properties"/> <bean id="studentDao" class="com.cy.dao.impl.StudentDaoImpl">
<property name="dataSource" ref="dataSource"></property>
</bean> <bean id="studentService" class="com.cy.service.impl.StudentServiceImpl">
<property name="studentDao" ref="studentDao"></property>
</bean> </beans>

测试代码不变,执行都ok;

2.NamedParameterJdbcTemplate 的使用:

1)StudentDaoImpl.java:

package com.cy.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List; import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import com.cy.dao.StudentDao;
import com.cy.model.Student; public class StudentDaoImpl implements StudentDao { private NamedParameterJdbcTemplate namedParameterJdbcTemplate; public void setNamedParameterJdbcTemplate(NamedParameterJdbcTemplate namedParameterJdbcTemplate) {
this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
} @Override
public int addStudent(Student student) {
String sql = "insert into t_student values (null, :name, :age)";
MapSqlParameterSource sps = new MapSqlParameterSource();
sps.addValue("name", student.getName())
.addValue("age", student.getAge());
return namedParameterJdbcTemplate.update(sql, sps);
} @Override
public int updateStudent(Student student) {
String sql = "update t_student set name=:name, age=:age where id =:id";
MapSqlParameterSource sps = new MapSqlParameterSource();
sps.addValue("name", student.getName())
.addValue("age", student.getAge())
.addValue("id", student.getId());
return namedParameterJdbcTemplate.update(sql, sps);
} @Override
public int deleteStudent(int id) {
String sql = "delete from t_student where id = :id";
MapSqlParameterSource sps = new MapSqlParameterSource();
sps.addValue("id", id);
return namedParameterJdbcTemplate.update(sql, sps);
} /**
* 查询所有的学生
*/
@Override
public List<Student> findStudents() {
String sql = "select * from t_student";
final List<Student> studentList = new ArrayList<Student>();
namedParameterJdbcTemplate.query(sql, new RowCallbackHandler(){ @Override
public void processRow(ResultSet rs) throws SQLException {
Student student = new Student();
student.setId(rs.getInt("id"));
student.setName(rs.getString("name"));
student.setAge(rs.getInt("age"));
studentList.add(student);
} });
return studentList;
} }

2)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:aop="http://www.springframework.org/schema/aop"
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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean> <context:property-placeholder location="jdbc.properties"/> <bean id="namedParameterJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
<constructor-arg ref="dataSource"></constructor-arg>
</bean> <bean id="studentDao" class="com.cy.dao.impl.StudentDaoImpl">
<property name="namedParameterJdbcTemplate" ref="namedParameterJdbcTemplate"></property>
</bean> <bean id="studentService" class="com.cy.service.impl.StudentServiceImpl">
<property name="studentDao" ref="studentDao"></property>
</bean> </beans>

测试代码不变,测试ok

----------------------------------

峰Spring4学习(7)spring对JDBC的支持的更多相关文章

  1. 1.Spring对JDBC整合支持

    1.Spring对JDBC整合支持 Spring对DAO提供哪些支持 1)Spring对DAO异常提供统一处理 2)Spring对DAO编写提供支持的抽象类 3)提高编程效率,减少DAO编码量 Spr ...

  2. 8.Spring对JDBC的支持和事务

    1.Spring对JDBC的支持 DAO : Spring中对数据访问对象(DAO)的支持旨在简化Spring与数据访问技术的操作,使JDBC.Hibernate.JPA和JDO等采用统一的方式访问 ...

  3. [原创]java WEB学习笔记109:Spring学习---spring对JDBC的支持:使用 JdbcTemplate 查询数据库,简化 JDBC 模板查询,在 JDBC 模板中使用具名参数两种实现

    本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用 内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系. 本人互联网技术爱 ...

  4. Spring对jdbc的支持

    Spring对jdbc技术提供了很好的支持. 体现在: 1)Spring对c3p连接池的支持很完善: 2)Spring对jdbc提供了JdbcTemplate,来简化jdbc操作: 1.使用步骤 1) ...

  5. spring 对JDBC的支持 (8)

    目录 一.jdbc的简介 二.jdbcTemplate 的使用 2.1 maven 引入spring - jdbc ,c3p0 ,数据库mysql驱动 2.2 配置 数据源以及jdbcTemplate ...

  6. 峰Spring4学习(8)spring对事务的支持

    一.事务简介: 二.编程式事务管理: 例子 1.需求:模拟转账,张三向李四转账50元: 数据库中存在t_count表: 代码实现: BankDao.java: package com.cy.dao; ...

  7. 峰Spring4学习(4)spring自动装配

    一.自动装配: Model类: People.java: package com.cy.entity; public class People { private int id; private St ...

  8. 峰Spring4学习(6)spring AOP的应用例子

    一.AOP简介: 二.AOP实例: 三.使用的例子 需求:在student添加的前后,打印日志信息: 0)spring AOP需要引用的jar包: 1)StudentService.java接口: p ...

  9. Spring框架学习笔记(9)——Spring对JDBC的支持

    一.使用JdbcTemplate和JdbcDaoSupport 1.配置并连接数据库 ①创建项目并添加jar包,要比之前Spring项目多添加两个jar包c3p0-0.9.1.2.jar和mysql- ...

随机推荐

  1. springboot logback + log4j2日志管理

    springboot的web项目中自带了日志组件: 我们看一下,springboot中找到日志组件. <dependency> <groupId>org.springframe ...

  2. CSS 再学习,文本处理

    文本缩进(对p,div有效:对span无效) p {text-indent: 5em;} Tips:一般来说,可以为所有块级元素应用 text-indent,但无法将该属性应用于行内元素(span), ...

  3. 使用向量化的 if:ifelse

    进行分支计算的一个替代方法是 ifelse( ).这个函数接收一个逻辑向量作为判定条件,并且返回一个向量.对于逻辑判定条件内的每一个元素,若是 TRUE,则选择第 2个参数 yes 中所对应的元素:若 ...

  4. Android:你好,androidX!再见,android.support

    1.AndroidX简介 点击查看Android文档中对androidx的简介 按照官方文档说明 androidx 是对 android.support.xxx 包的整理后产物.由于之前的suppor ...

  5. Java网络编程和NIO详解3:IO模型与Java网络编程模型

    Java网络编程和NIO详解3:IO模型与Java网络编程模型 基本概念说明 用户空间与内核空间 现在操作系统都是采用虚拟存储器,那么对32位操作系统而言,它的寻址空间(虚拟存储空间)为4G(2的32 ...

  6. 3321 Apple Tree 树状数组

    LIANJIE:http://poj.org/problem?id=3321 给你一个多叉树,每个叉和叶子节点有一颗苹果.然后给你两个操作,一个是给你C清除某节点上的苹果或者添加(此节点上有苹果则清除 ...

  7. C# 简单生成双色球代码

    红球篮球产生代码 public class TestD { //产生几组数据 public void getzhu( int num) { ; m < num; m++) { getred(); ...

  8. 在ubuntu16中部署Django使用memcached作为缓存

    Django支持很多缓存系统,如 文件系统缓存. 数据库缓存. 内存缓存(Memcached),其中,Memcached是最快的,没有之一,是绝配.因为所有的缓存数据都放在内存,没有了IO延迟,也没有 ...

  9. Toncat-OpenSSL双向认证配置(iOS)

    OpenSSL生成证书 要生成证书的目录下建立几个文件和文件夹,有./demoCA/ ./demoCA/newcerts/ ./demoCA/private/ ./demoCA/index.txt ( ...

  10. [置顶] 【机器学习PAI实践十一】机器学习PAI为你自动写歌词,妈妈再也不用担心我的freestyle了(提供数据、代码

    背景 最近互联网上出现一个热词就是"freestyle",源于一个比拼rap的综艺节目.在节目中需要大量考验选手的freestyle能力,freestyle指的是rapper即兴的 ...