[Spring学习笔记 6 ] Spring JDBC 详解
项目使用maven管理,pom.xml和项目组织如下:
- <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <groupId>com.amos.spring</groupId>
- <artifactId>Lspring_JDBC</artifactId>
- <version>0.0.1-SNAPSHOT</version>
- <packaging>jar</packaging>
- <name>Lspring_JDBC</name>
- <url>http://maven.apache.org</url>
- <properties>
- <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
- </properties>
- <dependencies>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>4.2</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-jdbc</artifactId>
- <version>3.2.4.RELEASE</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-context</artifactId>
- <version>3.2.4.RELEASE</version>
- </dependency>
- <dependency>
- <groupId> org.aspectj</groupId>
- <artifactId> aspectjweaver</artifactId>
- <version> 1.6.11</version>
- </dependency>
- <dependency>
- <groupId>commons-dbcp</groupId>
- <artifactId>commons-dbcp</artifactId>
- <version>1.2.2</version>
- </dependency>
- <dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- <version>5.1.24</version>
- </dependency>
- </dependencies>
- </project>
逻辑步骤如下:
1.直接看代码:传统操作数据库方式
- package com.amos.spring.dao;
- import java.sql.Connection;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
- import javax.sql.DataSource;
- import org.apache.commons.dbcp.BasicDataSource;
- /**
- * @ClassName: 传统的操作数据库的方式
- * @Description: TODO
- * @author: amosli
- * @email:amosli@infomorrow.com
- * @date Nov 28, 2013 2:03:23 AM
- */
- public class DbUtil {
- private static DataSource datasource;
- static {
- // 初始化连接池
- BasicDataSource dSource = new BasicDataSource();
- // 设置连接池的属性
- dSource.setDriverClassName("com.mysql.jdbc.Driver");
- dSource.setUrl("jdbc:mysql:///spring_learn");
- dSource.setUsername("root");
- dSource.setPassword("root");
- datasource = dSource;
- }
- public static Connection getConn() throws SQLException {
- return datasource.getConnection();
- }
- public static void close(ResultSet rs, Statement stmt, Connection conn) {
- if (rs != null) {
- try {
- rs.close();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- if (stmt != null) {
- try {
- stmt.close();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- if (conn != null) {
- try {
- conn.close();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- }
- }
2.定义一个person接口
- package com.amos.spring.dao;
- import java.util.List;
- import com.amos.spring.model.Person;
- /**
- * @ClassName: IpersonDao
- * @Description: TODO
- * @author: amosli
- * @email:amosli@infomorrow.com
- * @date Nov 27, 2013 12:35:48 AM
- */
- public interface IpersonDao {
- void save(Person p);
- void update(Long id, Person p);
- void delete(Long id);
- List<Person> loadAll();
- }
3.使用最原始的操作数据库方式
- package com.amos.spring.impl;
- import java.sql.Connection;
- import java.sql.SQLException;
- import java.sql.Statement;
- import java.util.List;
- import com.amos.spring.dao.DbUtil;
- import com.amos.spring.dao.IpersonDao;
- import com.amos.spring.model.Person;
- /**
- * @ClassName: PersonDaoImplJdbcOld
- * @Description: 最原始的操作
- * @author: amosli
- * @email:amosli@infomorrow.com
- * @date Nov 28, 2013 12:15:20 AM
- */
- public class PersonDaoImplJdbcOld implements IpersonDao {
- public void save(Person p) {
- // 获得连接
- // 获得一个连接Connection
- Connection conn = null;
- Statement stmt = null;
- try {
- conn = DbUtil.getConn();
- // 开取事务
- conn.setAutoCommit(false);
- // 初始化相关的Statment对象
- stmt = conn.createStatement();
- String sql = "insert into person(name,age) values('" + p.getName() + "'," + p.getAge() + ")";
- stmt.executeUpdate(sql);
- // 提交事务
- conn.commit();
- } catch (Exception e) {
- try {
- if (conn != null)
- conn.rollback();
- } catch (SQLException e1) {
- e1.printStackTrace();
- }
- } finally {
- DbUtil.close(null, stmt, conn);
- }
- }
- public void update(Long id, Person p) {
- // 获得一个连接Connection
- Connection conn = null;
- Statement stmt = null;
- try {
- conn = DbUtil.getConn();
- // 开取事务
- conn.setAutoCommit(false);
- // 初始化相关的Statment对象
- stmt = conn.createStatement();
- String sql = "update person set name = '" + p.getName() + "',age='" + p.getAge() + "' where id='" + p.getId() + "'";
- stmt.executeUpdate(sql);
- // 提交事务
- conn.commit();
- } catch (Exception e) {
- try {
- if (conn != null)
- conn.rollback();
- } catch (SQLException e1) {
- e1.printStackTrace();
- }
- } finally {
- DbUtil.close(null, stmt, conn);
- }
- }
- public void delete(Long id) {
- Connection conn = null;
- Statement stmt = null;
- try {
- conn = DbUtil.getConn();
- // 开取事务
- conn.setAutoCommit(false);
- // 初始化相关的Statment对象
- stmt = conn.createStatement();
- String sql = "delete person where id='"+id+"'";
- stmt.executeUpdate(sql);
- // 提交事务
- conn.commit();
- } catch (Exception e) {
- try {
- if (conn != null)
- conn.rollback();
- } catch (SQLException e1) {
- e1.printStackTrace();
- }
- } finally {
- DbUtil.close(null, stmt, conn);
- }
- }
- public List<Person> loadAll() {
- // TODO Auto-generated method stub
- return null;
- }
- }
4.发现有很多冗余的地方,关于数据库的开启关闭都是相同的,怎么抽象出来共有的地方???
定义一个接口,使用内部类实现这个接口,然后调用这个方法。
- package com.amos.spring.impl;
- import java.sql.Connection;
- import java.sql.SQLException;
- import java.sql.Statement;
- import java.util.List;
- import com.amos.spring.dao.DbUtil;
- import com.amos.spring.dao.IpersonDao;
- import com.amos.spring.model.Person;
- /**
- * @ClassName: PersonDaoImplJdbc
- * @Description: 把相同的操作封装成一个接口,用内部 类实现接口
- * @author: amosli
- * @email:amosli@infomorrow.com
- * @date Nov 27, 2013 11:37:50 PM
- */
- public class PersonDaoImplJdbc implements IpersonDao {
- interface UpdateOperation {
- /**
- * 把各种各样的操作封装成一个接口
- *
- * @param stmt
- * @throws SQLException
- */
- void execute(Statement stmt) throws SQLException;
- }
- /**
- * 执行数据库操作
- */
- public void excuteUpdate(UpdateOperation operation) {
- // 获得一个连接Connection
- Connection conn = null;
- Statement stmt = null;
- try {
- conn = DbUtil.getConn();
- // 开取事务
- conn.setAutoCommit(false);
- // 初始化相关的Statment对象
- stmt = conn.createStatement();
- // 执行具体的操作
- operation.execute(stmt);
- // 提交事务
- conn.commit();
- } catch (Exception e) {
- try {
- if (conn != null)
- conn.rollback();
- } catch (SQLException e1) {
- e1.printStackTrace();
- }
- } finally {
- DbUtil.close(null, stmt, conn);
- }
- }
- public void save(final Person p) {
- // save中就只有核心的业务代码了
- excuteUpdate(new UpdateOperation() {
- public void execute(Statement stmt) throws SQLException {
- String sql = "insert into person(name,age) values('" + p.getName() + "'," + p.getAge() + ")";
- stmt.executeUpdate(sql);
- }
- });
- }
- public void update(final Long id, final Person p) {
- excuteUpdate(new UpdateOperation() {
- public void execute(Statement stmt) throws SQLException {
- String sql = "update person set name = '" + p.getName() + "',age='" + p.getAge() + "' where id='" + id + "'";
- stmt.executeUpdate(sql);
- }
- });
- }
- public void delete(final Long id) {
- excuteUpdate(new UpdateOperation() {
- public void execute(Statement stmt) throws SQLException {
- String sql = "delete person where id='" + id + "'";
- stmt.executeUpdate(sql);
- }
- });
- }
- public List<Person> loadAll() {
- return null;
- }
- }
5.怎么才能进一步优化代码???那就把刚才核心代码抽象成一个类,不仅person可以使用其他类也可以使用
如下代码:
- package com.amos.spring.impl;
- import java.sql.Connection;
- import java.sql.SQLException;
- import java.sql.Statement;
- import java.util.List;
- import com.amos.spring.dao.DbUtil;
- import com.amos.spring.dao.IpersonDao;
- import com.amos.spring.model.Person;
- /**
- * @ClassName: PersonDaoImplJdbcTemplate
- * @Description: 代码继续优化,把实现接口的方法提取出来
- * @author: amosli
- * @email:amosli@infomorrow.com
- * @date Nov 27, 2013 11:51:06 PM
- */
- public class PersonDaoImplJdbcTemplate implements IpersonDao {
- interface UpdateOperation {
- /**
- * 把各种各样的操作封装成一个接口
- *
- * @param stmt
- * @throws SQLException
- */
- void execute(Statement stmt) throws SQLException;
- }
- /**
- * 执行数据库操作
- */
- public void excuteUpdate(UpdateOperation operation) {
- // 获得一个连接Connection
- Connection conn = null;
- Statement stmt = null;
- try {
- conn = DbUtil.getConn();
- // 开取事务
- conn.setAutoCommit(false);
- // 初始化相关的Statment对象
- stmt = conn.createStatement();
- // 执行具体的操作
- operation.execute(stmt);
- // 提交事务
- conn.commit();
- } catch (Exception e) {
- try {
- if (conn != null)
- conn.rollback();
- } catch (SQLException e1) {
- e1.printStackTrace();
- }
- } finally {
- DbUtil.close(null, stmt, conn);
- }
- }
- public void excuteSql(final String sql) {
- excuteUpdate(new UpdateOperation() {
- public void execute(Statement stmt) throws SQLException {
- stmt.executeUpdate(sql);
- }
- });
- }
- public void save(final Person p) {
- // save中就只有核心的业务代码了
- String sql = "insert into person(name,age) values('" + p.getName() + "'," + p.getAge() + ")";
- excuteSql(sql);
- }
- public void update(final Long id, final Person p) {
- String sql = "update person set name = '" + p.getName() + "',age='" + p.getAge() + "' where id='" + id + "'";
- excuteSql(sql);
- }
- public void delete(final Long id) {
- String sql = "delete person where id='" + id + "'";
- excuteSql(sql);
- }
- public List<Person> loadAll() {
- return null;
- }
- }
6.写个testcase测试下吧:
- package com.amos.spring.dao;
- import com.amos.spring.impl.PersonDaoImplJdbcTemplateBest;
- import com.amos.spring.model.Person;
- /**
- * @ClassName: PersonDaoTest
- * @Description: 把关于数据库操作的类封装起来进行调用
- * @author: amosli
- * @email:amosli@infomorrow.com
- * @date Nov 28, 2013 1:59:04 AM
- */
- public class PersonDaoTest {
- private static IpersonDao dao;
- public static void main(String args[]) {
- dao = new PersonDaoImplJdbcTemplateBest();
- Person person = new Person();
- person.setName("运哥");
- person.setAge(29);
- dao.save(person);
- }
- }
然后去查看数据库即可。
数据库非常简单,person数据库生成代码:
- DROP TABLE IF EXISTS `person`;
- CREATE TABLE `person` (
- `id` int(11) NOT NULL AUTO_INCREMENT,
- `name` varchar(1000) DEFAULT NULL,
- `age` int(11) DEFAULT NULL,
- PRIMARY KEY (`id`)
- ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=gbk;
- -- ----------------------------
- -- Records of person
- -- ----------------------------
- INSERT INTO `person` VALUES ('1', '运哥', '23');
7.使用spring 又该如何呢?使用JdbcTemplate模板
- package com.amos.spring.impl;
- import java.util.List;
- import org.springframework.jdbc.core.JdbcTemplate;
- import com.amos.spring.dao.IpersonDao;
- import com.amos.spring.model.Person;
- /**
- * @ClassName: SpringJdbcTemplateBest
- * @Description: 使用spring 框架进行操作数据库
- * @author: amosli
- * @email:amosli@infomorrow.com
- * @date Nov 28, 2013 1:01:27 AM
- */
- public class SpringJdbcTemplateBest implements IpersonDao {
- private JdbcTemplate jdbcTemplate;
- public List<Person> loadAll() {
- return null;
- }
- public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
- this.jdbcTemplate = jdbcTemplate;
- }
- public void save(Person p) {
- String sql = "insert into person(name,age) values('" + p.getName() + "'," + p.getAge() + ")";
- System.out.println("save:" + sql);
- jdbcTemplate.update(sql);
- }
- public void update(Long id, Person p) {
- String sql = "update person set name = '" + p.getName() + "',age='" + p.getAge() + "' where id='" + id + "'";
- jdbcTemplate.update(sql);
- }
- public void delete(Long id) {
- String sql = "delete person where id='" + id + "'";
- jdbcTemplate.update(sql);
- }
- }
8.配置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" xmlns:context="http://www.springframework.org/schema/context"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.2.xsd
- ">
- <context:property-placeholder location="db.properties" />
- <!-- 配置连接池 -->
- <bean id="mydataSource" class="org.apache.commons.dbcp.BasicDataSource">
- <property name="driverClassName" value="${db.driverClassName}"></property>
- <property name="url" value="${db.url}"></property>
- <property name="username" value="${db.username}"></property>
- <property name="password" value="${db.password}"></property>
- </bean>
- <!-- 配置jdbctemplate -->
- <bean id="myjdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
- <property name="dataSource" ref="mydataSource"></property>
- </bean>
- <bean id="personDao" class="com.amos.spring.impl.SpringJdbcTemplateBest">
- <property name="jdbcTemplate" ref="myjdbcTemplate"></property>
- </bean>
- </beans>
db.properties:
- db.driverClassName=com.mysql.jdbc.Driver
- db.url=jdbc:mysql:///spring_learn
- db.username=root
- db.password=root
9.写个testcase测试一下:
- package com.amos.spring.dao;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
- import com.amos.spring.model.Person;
- public class SpringPersonDaoTest {
- private static IpersonDao dao;
- // @Test
- public static void main(String args[]){
- ApplicationContext acx = new ClassPathXmlApplicationContext("bean.xml");
- dao = acx.getBean(IpersonDao.class);
- Person person = new Person();
- person.setName("运哥");
- person.setAge(33);
- dao.save(person);
- }
- }
[Spring学习笔记 6 ] Spring JDBC 详解的更多相关文章
- IP2——IP地址和子网划分学习笔记之《子网掩码详解》
2018-05-04 16:21:21 在学习掌握了前面的<进制计数><IP地址详解>这两部分知识后,要学习子网划分,首先就要必须知道子网掩码,只有掌握了子网掩码这部分内容 ...
- spring学习笔记(一) Spring概述
博主Spring学习笔记整理大部分内容来自Spring实战(第四版)这本书. 强烈建议新手购入或者需要电子书的留言. 在学习Spring之前,我们要了解这么几个问题:什么是Spring?Spring ...
- Java架构师之路 Spring学习笔记(一) Spring介绍
前言 这是一篇原创的Spring学习笔记.主要记录我学习Spring4.0的过程.本人有四年的Java Web开发经验,最近在面试中遇到面试官总会问一些简单但我不会的Java问题,让我觉得有必要重新审 ...
- [Spring学习笔记 5 ] Spring AOP 详解1
知识点回顾:一.IOC容器---DI依赖注入:setter注入(属性注入)/构造子注入/字段注入(注解 )/接口注入 out Spring IOC容器的使用: A.完全使用XML文件来配置容器所要管理 ...
- [Spring学习笔记 1 ] Spring 简介,初步知识--Ioc容器详解 基本原理。
一.Spring Ioc容器详解(1) 20131105 1.一切都是Bean Bean可是一个字符串或者是数字,一般是一些业务组件. 粒度一般比较粗. 2.Bean的名称 xml配置文件中,id属性 ...
- MyBatis学习笔记2--配置环境详解
1.MyBatis-config.xml详解 一个完整的配置文件如下所示 <configuration> <!-- <properties resource="jdb ...
- [读书笔记]C#学习笔记三: C#类型详解..
前言 这次分享的主要内容有五个, 分别是值类型和引用类型, 装箱与拆箱,常量与变量,运算符重载,static字段和static构造函数. 后期的分享会针对于C#2.0 3.0 4.0 等新特性进行. ...
- CDN学习笔记二(技术详解)
一本好的入门书是带你进入陌生领域的明灯,<CDN技术详解>绝对是带你进入CDN行业的那盏最亮的明灯.因此,虽然只是纯粹的重点抄录,我也要把<CDN技术详解>的精华放上网.公诸同 ...
- C#学习笔记二: C#类型详解
前言 这次分享的主要内容有五个, 分别是值类型和引用类型, 装箱与拆箱,常量与变量,运算符重载,static字段和static构造函数. 后期的分享会针对于C#2.0 3.0 4.0 等新特性进行. ...
- 【Java学习笔记之三十三】详解Java中try,catch,finally的用法及分析
这一篇我们将会介绍java中try,catch,finally的用法 以下先给出try,catch用法: try { //需要被检测的异常代码 } catch(Exception e) { //异常处 ...
随机推荐
- CSS布局中一个简单的应用BFC的例子
什么是BFC BFC(Block Formatting Context),简单讲,它是提供了一个独立布局的环境,每个BFC都遵守同一套布局规则.例如,在同一个BFC内,盒子会一个挨着一个的排,相邻盒子 ...
- 手把手实现腾讯qq拖拽删去效果(一)
qq拖拽删除的效果,简单又好用,今天我就叫大家实现吧. 这个滑动效果,有何难点了,就是响应每行的点击事件了,为了完成这个任务,并且能够实现动画的效果了,我重写了一个slideview这个控件,这个控件 ...
- 【算法】Java-Redis-Hash算法对比-参考资料
Java-Redis-Hash算法对比-参考资料 redis java map 红黑树_百度搜索 java使用redis缓存(String,bean,list,map) - CSDN博客 redis ...
- 【Spark】SparkStreaming-如何使用checkpoint
SparkStreaming-如何使用checkpoint sparkstreaming checkpoint 默认_百度搜索 spark streaming中使用checkpoint - HarkL ...
- Fixing the JavaScript typeof operator
https://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/javascript 类 ...
- HttpWebRequest: Remote server returns error 503 Server Unavailable
I have a client server application written in C# .Net 2.0. I have had the client/server response/r ...
- Mongoose vs mongodb native driver – what to prefer?
Paul Shan 7th Jun 2015 Mongoose or mongodb native driver, which one to use? This is one of the ini ...
- log4j.xml写入数据库,只有SQL和参数,无其他信息
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE log4j:configuration SY ...
- Mac WIn7 QQ聊天记录互导 聊天记录合并
也许等哪天老了回过头来看看.说不定还有一丝欢乐. 有几个方法可以实现 一.dropbox数据同步 二.QQ会员 三.下面方法 1.因为现在的Mac QQ还不支持聊天记录的导入导出.所以只能手动了 如果 ...
- android布局 - fill_parent/match_paren/wrap_content的区别
三个属性都用来适应视图的水平或垂直大小,一个以视图的内容或尺寸为基础的布局比精确地指定视图范围更加方便. 1)fill_parent 设置一个构件的布局为fill_parent将强制性地使构件扩展,以 ...