项目使用maven管理,pom.xml和项目组织如下:

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  3. <modelVersion>4.0.0</modelVersion>
  4.  
  5. <groupId>com.amos.spring</groupId>
  6. <artifactId>Lspring_JDBC</artifactId>
  7. <version>0.0.1-SNAPSHOT</version>
  8. <packaging>jar</packaging>
  9.  
  10. <name>Lspring_JDBC</name>
  11. <url>http://maven.apache.org</url>
  12.  
  13. <properties>
  14. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  15. </properties>
  16.  
  17. <dependencies>
  18. <dependency>
  19. <groupId>junit</groupId>
  20. <artifactId>junit</artifactId>
  21. <version>4.2</version>
  22. <scope>test</scope>
  23. </dependency>
  24. <dependency>
  25. <groupId>org.springframework</groupId>
  26. <artifactId>spring-jdbc</artifactId>
  27. <version>3.2.4.RELEASE</version>
  28. </dependency>
  29.  
  30. <dependency>
  31. <groupId>org.springframework</groupId>
  32. <artifactId>spring-context</artifactId>
  33. <version>3.2.4.RELEASE</version>
  34. </dependency>
  35. <dependency>
  36. <groupId> org.aspectj</groupId>
  37. <artifactId> aspectjweaver</artifactId>
  38. <version> 1.6.11</version>
  39. </dependency>
  40. <dependency>
  41. <groupId>commons-dbcp</groupId>
  42. <artifactId>commons-dbcp</artifactId>
  43. <version>1.2.2</version>
  44. </dependency>
  45. <dependency>
  46. <groupId>mysql</groupId>
  47. <artifactId>mysql-connector-java</artifactId>
  48. <version>5.1.24</version>
  49. </dependency>
  50.  
  51. </dependencies>
  52. </project>

逻辑步骤如下:

1.直接看代码:传统操作数据库方式

  1. package com.amos.spring.dao;
  2.  
  3. import java.sql.Connection;
  4. import java.sql.ResultSet;
  5. import java.sql.SQLException;
  6. import java.sql.Statement;
  7.  
  8. import javax.sql.DataSource;
  9.  
  10. import org.apache.commons.dbcp.BasicDataSource;
  11.  
  12. /**
  13. * @ClassName: 传统的操作数据库的方式
  14. * @Description: TODO
  15. * @author: amosli
  16. * @email:amosli@infomorrow.com
  17. * @date Nov 28, 2013 2:03:23 AM
  18. */
  19. public class DbUtil {
  20. private static DataSource datasource;
  21. static {
  22. // 初始化连接池
  23. BasicDataSource dSource = new BasicDataSource();
  24. // 设置连接池的属性
  25. dSource.setDriverClassName("com.mysql.jdbc.Driver");
  26. dSource.setUrl("jdbc:mysql:///spring_learn");
  27. dSource.setUsername("root");
  28. dSource.setPassword("root");
  29. datasource = dSource;
  30. }
  31.  
  32. public static Connection getConn() throws SQLException {
  33. return datasource.getConnection();
  34. }
  35.  
  36. public static void close(ResultSet rs, Statement stmt, Connection conn) {
  37. if (rs != null) {
  38. try {
  39. rs.close();
  40. } catch (SQLException e) {
  41. e.printStackTrace();
  42. }
  43. }
  44. if (stmt != null) {
  45. try {
  46. stmt.close();
  47. } catch (SQLException e) {
  48. e.printStackTrace();
  49. }
  50. }
  51. if (conn != null) {
  52. try {
  53. conn.close();
  54. } catch (SQLException e) {
  55. e.printStackTrace();
  56. }
  57. }
  58. }
  59. }

2.定义一个person接口

  1. package com.amos.spring.dao;
  2.  
  3. import java.util.List;
  4.  
  5. import com.amos.spring.model.Person;
  6.  
  7. /**
  8. * @ClassName: IpersonDao
  9. * @Description: TODO
  10. * @author: amosli
  11. * @email:amosli@infomorrow.com
  12. * @date Nov 27, 2013 12:35:48 AM
  13. */
  14. public interface IpersonDao {
  15. void save(Person p);
  16.  
  17. void update(Long id, Person p);
  18.  
  19. void delete(Long id);
  20.  
  21. List<Person> loadAll();
  22.  
  23. }

3.使用最原始的操作数据库方式

  1. package com.amos.spring.impl;
  2.  
  3. import java.sql.Connection;
  4. import java.sql.SQLException;
  5. import java.sql.Statement;
  6. import java.util.List;
  7.  
  8. import com.amos.spring.dao.DbUtil;
  9. import com.amos.spring.dao.IpersonDao;
  10. import com.amos.spring.model.Person;
  11.  
  12. /**
  13. * @ClassName: PersonDaoImplJdbcOld
  14. * @Description: 最原始的操作
  15. * @author: amosli
  16. * @email:amosli@infomorrow.com
  17. * @date Nov 28, 2013 12:15:20 AM
  18. */
  19. public class PersonDaoImplJdbcOld implements IpersonDao {
  20.  
  21. public void save(Person p) {
  22. // 获得连接
  23. // 获得一个连接Connection
  24. Connection conn = null;
  25. Statement stmt = null;
  26. try {
  27. conn = DbUtil.getConn();
  28. // 开取事务
  29. conn.setAutoCommit(false);
  30. // 初始化相关的Statment对象
  31. stmt = conn.createStatement();
  32. String sql = "insert into person(name,age) values('" + p.getName() + "'," + p.getAge() + ")";
  33. stmt.executeUpdate(sql);
  34. // 提交事务
  35. conn.commit();
  36. } catch (Exception e) {
  37. try {
  38. if (conn != null)
  39. conn.rollback();
  40. } catch (SQLException e1) {
  41. e1.printStackTrace();
  42. }
  43. } finally {
  44. DbUtil.close(null, stmt, conn);
  45. }
  46. }
  47.  
  48. public void update(Long id, Person p) {
  49. // 获得一个连接Connection
  50. Connection conn = null;
  51. Statement stmt = null;
  52. try {
  53. conn = DbUtil.getConn();
  54. // 开取事务
  55. conn.setAutoCommit(false);
  56. // 初始化相关的Statment对象
  57. stmt = conn.createStatement();
  58. String sql = "update person set name = '" + p.getName() + "',age='" + p.getAge() + "' where id='" + p.getId() + "'";
  59. stmt.executeUpdate(sql);
  60. // 提交事务
  61. conn.commit();
  62. } catch (Exception e) {
  63. try {
  64. if (conn != null)
  65. conn.rollback();
  66. } catch (SQLException e1) {
  67. e1.printStackTrace();
  68. }
  69. } finally {
  70. DbUtil.close(null, stmt, conn);
  71. }
  72. }
  73.  
  74. public void delete(Long id) {
  75. Connection conn = null;
  76. Statement stmt = null;
  77. try {
  78. conn = DbUtil.getConn();
  79. // 开取事务
  80. conn.setAutoCommit(false);
  81. // 初始化相关的Statment对象
  82. stmt = conn.createStatement();
  83. String sql = "delete person where id='"+id+"'";
  84. stmt.executeUpdate(sql);
  85. // 提交事务
  86. conn.commit();
  87. } catch (Exception e) {
  88. try {
  89. if (conn != null)
  90. conn.rollback();
  91. } catch (SQLException e1) {
  92. e1.printStackTrace();
  93. }
  94. } finally {
  95. DbUtil.close(null, stmt, conn);
  96. }
  97. }
  98.  
  99. public List<Person> loadAll() {
  100. // TODO Auto-generated method stub
  101. return null;
  102. }
  103.  
  104. }

4.发现有很多冗余的地方,关于数据库的开启关闭都是相同的,怎么抽象出来共有的地方???

定义一个接口,使用内部类实现这个接口,然后调用这个方法。

  1. package com.amos.spring.impl;
  2.  
  3. import java.sql.Connection;
  4. import java.sql.SQLException;
  5. import java.sql.Statement;
  6. import java.util.List;
  7.  
  8. import com.amos.spring.dao.DbUtil;
  9. import com.amos.spring.dao.IpersonDao;
  10. import com.amos.spring.model.Person;
  11.  
  12. /**
  13. * @ClassName: PersonDaoImplJdbc
  14. * @Description: 把相同的操作封装成一个接口,用内部 类实现接口
  15. * @author: amosli
  16. * @email:amosli@infomorrow.com
  17. * @date Nov 27, 2013 11:37:50 PM
  18. */
  19. public class PersonDaoImplJdbc implements IpersonDao {
  20.  
  21. interface UpdateOperation {
  22. /**
  23. * 把各种各样的操作封装成一个接口
  24. *
  25. * @param stmt
  26. * @throws SQLException
  27. */
  28. void execute(Statement stmt) throws SQLException;
  29. }
  30.  
  31. /**
  32. * 执行数据库操作
  33. */
  34. public void excuteUpdate(UpdateOperation operation) {
  35. // 获得一个连接Connection
  36. Connection conn = null;
  37. Statement stmt = null;
  38. try {
  39. conn = DbUtil.getConn();
  40. // 开取事务
  41. conn.setAutoCommit(false);
  42. // 初始化相关的Statment对象
  43. stmt = conn.createStatement();
  44. // 执行具体的操作
  45. operation.execute(stmt);
  46. // 提交事务
  47. conn.commit();
  48. } catch (Exception e) {
  49. try {
  50. if (conn != null)
  51. conn.rollback();
  52. } catch (SQLException e1) {
  53. e1.printStackTrace();
  54. }
  55. } finally {
  56. DbUtil.close(null, stmt, conn);
  57. }
  58. }
  59.  
  60. public void save(final Person p) {
  61. // save中就只有核心的业务代码了
  62. excuteUpdate(new UpdateOperation() {
  63. public void execute(Statement stmt) throws SQLException {
  64. String sql = "insert into person(name,age) values('" + p.getName() + "'," + p.getAge() + ")";
  65. stmt.executeUpdate(sql);
  66. }
  67. });
  68. }
  69.  
  70. public void update(final Long id, final Person p) {
  71. excuteUpdate(new UpdateOperation() {
  72. public void execute(Statement stmt) throws SQLException {
  73. String sql = "update person set name = '" + p.getName() + "',age='" + p.getAge() + "' where id='" + id + "'";
  74. stmt.executeUpdate(sql);
  75. }
  76. });
  77. }
  78.  
  79. public void delete(final Long id) {
  80. excuteUpdate(new UpdateOperation() {
  81. public void execute(Statement stmt) throws SQLException {
  82. String sql = "delete person where id='" + id + "'";
  83. stmt.executeUpdate(sql);
  84. }
  85. });
  86.  
  87. }
  88.  
  89. public List<Person> loadAll() {
  90. return null;
  91. }
  92.  
  93. }

5.怎么才能进一步优化代码???那就把刚才核心代码抽象成一个类,不仅person可以使用其他类也可以使用

如下代码:

  1. package com.amos.spring.impl;
  2.  
  3. import java.sql.Connection;
  4. import java.sql.SQLException;
  5. import java.sql.Statement;
  6. import java.util.List;
  7.  
  8. import com.amos.spring.dao.DbUtil;
  9. import com.amos.spring.dao.IpersonDao;
  10. import com.amos.spring.model.Person;
  11.  
  12. /**
  13. * @ClassName: PersonDaoImplJdbcTemplate
  14. * @Description: 代码继续优化,把实现接口的方法提取出来
  15. * @author: amosli
  16. * @email:amosli@infomorrow.com
  17. * @date Nov 27, 2013 11:51:06 PM
  18. */
  19. public class PersonDaoImplJdbcTemplate implements IpersonDao {
  20.  
  21. interface UpdateOperation {
  22. /**
  23. * 把各种各样的操作封装成一个接口
  24. *
  25. * @param stmt
  26. * @throws SQLException
  27. */
  28. void execute(Statement stmt) throws SQLException;
  29. }
  30.  
  31. /**
  32. * 执行数据库操作
  33. */
  34. public void excuteUpdate(UpdateOperation operation) {
  35. // 获得一个连接Connection
  36. Connection conn = null;
  37. Statement stmt = null;
  38. try {
  39. conn = DbUtil.getConn();
  40. // 开取事务
  41. conn.setAutoCommit(false);
  42. // 初始化相关的Statment对象
  43. stmt = conn.createStatement();
  44. // 执行具体的操作
  45. operation.execute(stmt);
  46. // 提交事务
  47. conn.commit();
  48. } catch (Exception e) {
  49. try {
  50. if (conn != null)
  51. conn.rollback();
  52. } catch (SQLException e1) {
  53. e1.printStackTrace();
  54. }
  55. } finally {
  56. DbUtil.close(null, stmt, conn);
  57. }
  58. }
  59.  
  60. public void excuteSql(final String sql) {
  61. excuteUpdate(new UpdateOperation() {
  62. public void execute(Statement stmt) throws SQLException {
  63. stmt.executeUpdate(sql);
  64. }
  65. });
  66. }
  67.  
  68. public void save(final Person p) {
  69. // save中就只有核心的业务代码了
  70. String sql = "insert into person(name,age) values('" + p.getName() + "'," + p.getAge() + ")";
  71. excuteSql(sql);
  72. }
  73.  
  74. public void update(final Long id, final Person p) {
  75. String sql = "update person set name = '" + p.getName() + "',age='" + p.getAge() + "' where id='" + id + "'";
  76. excuteSql(sql);
  77. }
  78.  
  79. public void delete(final Long id) {
  80. String sql = "delete person where id='" + id + "'";
  81. excuteSql(sql);
  82. }
  83.  
  84. public List<Person> loadAll() {
  85. return null;
  86. }
  87.  
  88. }

6.写个testcase测试下吧:

  1. package com.amos.spring.dao;
  2.  
  3. import com.amos.spring.impl.PersonDaoImplJdbcTemplateBest;
  4. import com.amos.spring.model.Person;
  5.  
  6. /**
  7. * @ClassName: PersonDaoTest
  8. * @Description: 把关于数据库操作的类封装起来进行调用
  9. * @author: amosli
  10. * @email:amosli@infomorrow.com
  11. * @date Nov 28, 2013 1:59:04 AM
  12. */
  13. public class PersonDaoTest {
  14. private static IpersonDao dao;
  15.  
  16. public static void main(String args[]) {
  17. dao = new PersonDaoImplJdbcTemplateBest();
  18. Person person = new Person();
  19. person.setName("运哥");
  20. person.setAge(29);
  21. dao.save(person);
  22. }
  23. }

然后去查看数据库即可。

数据库非常简单,person数据库生成代码:

  1. DROP TABLE IF EXISTS `person`;
  2. CREATE TABLE `person` (
  3. `id` int(11) NOT NULL AUTO_INCREMENT,
  4. `name` varchar(1000) DEFAULT NULL,
  5. `age` int(11) DEFAULT NULL,
  6. PRIMARY KEY (`id`)
  7. ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=gbk;
  8.  
  9. -- ----------------------------
  10. -- Records of person
  11. -- ----------------------------
  12. INSERT INTO `person` VALUES ('1', '运哥', '23');

7.使用spring 又该如何呢?使用JdbcTemplate模板

  1. package com.amos.spring.impl;
  2.  
  3. import java.util.List;
  4.  
  5. import org.springframework.jdbc.core.JdbcTemplate;
  6.  
  7. import com.amos.spring.dao.IpersonDao;
  8. import com.amos.spring.model.Person;
  9.  
  10. /**
  11. * @ClassName: SpringJdbcTemplateBest
  12. * @Description: 使用spring 框架进行操作数据库
  13. * @author: amosli
  14. * @email:amosli@infomorrow.com
  15. * @date Nov 28, 2013 1:01:27 AM
  16. */
  17. public class SpringJdbcTemplateBest implements IpersonDao {
  18. private JdbcTemplate jdbcTemplate;
  19. public List<Person> loadAll() {
  20. return null;
  21. }
  22.  
  23. public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
  24. this.jdbcTemplate = jdbcTemplate;
  25. }
  26.  
  27. public void save(Person p) {
  28. String sql = "insert into person(name,age) values('" + p.getName() + "'," + p.getAge() + ")";
  29. System.out.println("save:" + sql);
  30. jdbcTemplate.update(sql);
  31. }
  32.  
  33. public void update(Long id, Person p) {
  34. String sql = "update person set name = '" + p.getName() + "',age='" + p.getAge() + "' where id='" + id + "'";
  35. jdbcTemplate.update(sql);
  36. }
  37.  
  38. public void delete(Long id) {
  39. String sql = "delete person where id='" + id + "'";
  40. jdbcTemplate.update(sql);
  41. }
  42.  
  43. }

8.配置bean.xml文件

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans
  5. http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
  6. http://www.springframework.org/schema/context
  7. http://www.springframework.org/schema/context/spring-context-3.2.xsd
  8. ">
  9. <context:property-placeholder location="db.properties" />
  10. <!-- 配置连接池 -->
  11. <bean id="mydataSource" class="org.apache.commons.dbcp.BasicDataSource">
  12. <property name="driverClassName" value="${db.driverClassName}"></property>
  13. <property name="url" value="${db.url}"></property>
  14. <property name="username" value="${db.username}"></property>
  15. <property name="password" value="${db.password}"></property>
  16. </bean>
  17. <!-- 配置jdbctemplate -->
  18. <bean id="myjdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
  19. <property name="dataSource" ref="mydataSource"></property>
  20. </bean>
  21. <bean id="personDao" class="com.amos.spring.impl.SpringJdbcTemplateBest">
  22. <property name="jdbcTemplate" ref="myjdbcTemplate"></property>
  23. </bean>
  24. </beans>

db.properties:

  1. db.driverClassName=com.mysql.jdbc.Driver
  2. db.url=jdbc:mysql:///spring_learn
  3. db.username=root
  4. db.password=root

9.写个testcase测试一下:

  1. package com.amos.spring.dao;
  2.  
  3. import org.springframework.context.ApplicationContext;
  4. import org.springframework.context.support.ClassPathXmlApplicationContext;
  5.  
  6. import com.amos.spring.model.Person;
  7.  
  8. public class SpringPersonDaoTest {
  9. private static IpersonDao dao;
  10. // @Test
  11. public static void main(String args[]){
  12. ApplicationContext acx = new ClassPathXmlApplicationContext("bean.xml");
  13. dao = acx.getBean(IpersonDao.class);
  14. Person person = new Person();
  15. person.setName("运哥");
  16. person.setAge(33);
  17. dao.save(person);
  18. }
  19. }

[Spring学习笔记 6 ] Spring JDBC 详解的更多相关文章

  1. IP2——IP地址和子网划分学习笔记之《子网掩码详解》

    2018-05-04 16:21:21   在学习掌握了前面的<进制计数><IP地址详解>这两部分知识后,要学习子网划分,首先就要必须知道子网掩码,只有掌握了子网掩码这部分内容 ...

  2. spring学习笔记(一) Spring概述

    博主Spring学习笔记整理大部分内容来自Spring实战(第四版)这本书.  强烈建议新手购入或者需要电子书的留言. 在学习Spring之前,我们要了解这么几个问题:什么是Spring?Spring ...

  3. Java架构师之路 Spring学习笔记(一) Spring介绍

    前言 这是一篇原创的Spring学习笔记.主要记录我学习Spring4.0的过程.本人有四年的Java Web开发经验,最近在面试中遇到面试官总会问一些简单但我不会的Java问题,让我觉得有必要重新审 ...

  4. [Spring学习笔记 5 ] Spring AOP 详解1

    知识点回顾:一.IOC容器---DI依赖注入:setter注入(属性注入)/构造子注入/字段注入(注解 )/接口注入 out Spring IOC容器的使用: A.完全使用XML文件来配置容器所要管理 ...

  5. [Spring学习笔记 1 ] Spring 简介,初步知识--Ioc容器详解 基本原理。

    一.Spring Ioc容器详解(1) 20131105 1.一切都是Bean Bean可是一个字符串或者是数字,一般是一些业务组件. 粒度一般比较粗. 2.Bean的名称 xml配置文件中,id属性 ...

  6. MyBatis学习笔记2--配置环境详解

    1.MyBatis-config.xml详解 一个完整的配置文件如下所示 <configuration> <!-- <properties resource="jdb ...

  7. [读书笔记]C#学习笔记三: C#类型详解..

    前言 这次分享的主要内容有五个, 分别是值类型和引用类型, 装箱与拆箱,常量与变量,运算符重载,static字段和static构造函数. 后期的分享会针对于C#2.0 3.0 4.0 等新特性进行. ...

  8. CDN学习笔记二(技术详解)

    一本好的入门书是带你进入陌生领域的明灯,<CDN技术详解>绝对是带你进入CDN行业的那盏最亮的明灯.因此,虽然只是纯粹的重点抄录,我也要把<CDN技术详解>的精华放上网.公诸同 ...

  9. C#学习笔记二: C#类型详解

    前言 这次分享的主要内容有五个, 分别是值类型和引用类型, 装箱与拆箱,常量与变量,运算符重载,static字段和static构造函数. 后期的分享会针对于C#2.0 3.0 4.0 等新特性进行. ...

  10. 【Java学习笔记之三十三】详解Java中try,catch,finally的用法及分析

    这一篇我们将会介绍java中try,catch,finally的用法 以下先给出try,catch用法: try { //需要被检测的异常代码 } catch(Exception e) { //异常处 ...

随机推荐

  1. CSS布局中一个简单的应用BFC的例子

    什么是BFC BFC(Block Formatting Context),简单讲,它是提供了一个独立布局的环境,每个BFC都遵守同一套布局规则.例如,在同一个BFC内,盒子会一个挨着一个的排,相邻盒子 ...

  2. 手把手实现腾讯qq拖拽删去效果(一)

    qq拖拽删除的效果,简单又好用,今天我就叫大家实现吧. 这个滑动效果,有何难点了,就是响应每行的点击事件了,为了完成这个任务,并且能够实现动画的效果了,我重写了一个slideview这个控件,这个控件 ...

  3. 【算法】Java-Redis-Hash算法对比-参考资料

    Java-Redis-Hash算法对比-参考资料 redis java map 红黑树_百度搜索 java使用redis缓存(String,bean,list,map) - CSDN博客 redis ...

  4. 【Spark】SparkStreaming-如何使用checkpoint

    SparkStreaming-如何使用checkpoint sparkstreaming checkpoint 默认_百度搜索 spark streaming中使用checkpoint - HarkL ...

  5. Fixing the JavaScript typeof operator

    https://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/javascript 类 ...

  6. 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 ...

  7. 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 ...

  8. log4j.xml写入数据库,只有SQL和参数,无其他信息

    <?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE log4j:configuration SY ...

  9. Mac WIn7 QQ聊天记录互导 聊天记录合并

    也许等哪天老了回过头来看看.说不定还有一丝欢乐. 有几个方法可以实现 一.dropbox数据同步 二.QQ会员 三.下面方法 1.因为现在的Mac QQ还不支持聊天记录的导入导出.所以只能手动了 如果 ...

  10. android布局 - fill_parent/match_paren/wrap_content的区别

    三个属性都用来适应视图的水平或垂直大小,一个以视图的内容或尺寸为基础的布局比精确地指定视图范围更加方便. 1)fill_parent 设置一个构件的布局为fill_parent将强制性地使构件扩展,以 ...