• JDBC模板技术:

    Spring框架中提供了很多持久层的模板类来简化编程,使用模板类编写程序会变的简单

    • template 模板
    • 都是Spring框架提供XxxTemplate

    提供了JDBC模板,Spring框架提供的

    • JdbcTemplate类,Connection 表示连接,管理事务 Statement ResultSet
  • 如何使用JDBC模板类?
  • 在数据库中新增表结构和数据
     DROP TABLE IF EXISTS `account`;
    CREATE TABLE `account` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `name` varchar(40) DEFAULT NULL,
    `money` double DEFAULT NULL,
    PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8; -- ----------------------------
    -- Records of account
    -- ----------------------------
    INSERT INTO `account` VALUES ('1', 'aaa', '1000');
    INSERT INTO `account` VALUES ('2', 'bbb', '1000');
    INSERT INTO `account` VALUES ('3', 'ccc', '1000');
    INSERT INTO `account` VALUES ('4', '熊大', '700');
    INSERT INTO `account` VALUES ('5', '熊二', '1200');
    INSERT INTO `account` VALUES ('6', '熊三', '800');
  • 创建一个普通的Maven工程,引入坐标
 <dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.2.RELEASE</version>
</dependency> <dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.13</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
</dependencies>
  • 使用Spring框架来管理模板类,Spring管理内置的连接池

     <?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"
    xmlns:aop="http://www.springframework.org/schema/aop"
    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
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--配置连接池-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql:///spring_db" />
    <property name="username" value="root" />
    <property name="password" value="root" />
    </bean>

    <!--配置jdbc模板-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    <property name="dataSource" ref="dataSource" />
    </bean>

    </beans>
  • 测试jdbcTemplate
    package cn.tx.test;

    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.jdbc.core.JdbcTemplate;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    ​ @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(value = "classpath:applicationContext_jdbc.xml")
    public class Demo1_1 {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
    * 测试的方式
    */
    @Test
    public void run1(){
    jdbcTemplate.update("insert into account values (null,?,?)","熊二",500);
    }

    }
  • Spring框架管理开源的连接池

  • 配置开源的连接池,使用Druid的连接池,引入坐标
    <dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.10</version>
    </dependency>
  • 新建 一个属性文件后缀为.properties。配置连接数据库的基本信息
     jdbc.driverClassName=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql:///spring_db
    jdbc.username=root
    jdbc.password=root
  • 在xml的文件中配置读取属性文件,连接数据库和配置jdbc模板
     <?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"
    xmlns:aop="http://www.springframework.org/schema/aop"
    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
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--配置连接池,使用的是Spring框架内置的连接池
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql:///spring_db" />
    <property name="username" value="root" />
    <property name="password" value="root" />
    </bean>
    -->

    <!--使用开源连接池
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql:///spring_db" />
    <property name="username" value="root" />
    <property name="password" value="root" />
    </bean>
    -->

    <!--加载属性文件
    <bean id="placeholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location" value="classpath:jdbc.properties" />
    </bean>
    -->

    <!--第二种写法:使用提供标签的方式-->
    <context:property-placeholder location="classpath:jdbc.properties" />

    <!--加载属性的文件-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
    <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>

    <!--配置jdbc模板-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    <property name="dataSource" ref="dataSource" />
    </bean>

    </beans>
  • 对数据的基本操作做测试,增删改查
    package cn.tx.test;

    import cn.tx.demo1.Account;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.jdbc.core.JdbcTemplate;
    import org.springframework.jdbc.core.RowMapper;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.List;
    ​ @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(value = "classpath:applicationContext_jdbc.xml")
    public class Demo1_1 {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
    * 测试的方式
    */
    @Test
    public void run1(){
    jdbcTemplate.update("insert into account values (null,?,?)","熊四",800);
    }

    /**
    * 修改
    */
    @Test
    public void run2(){
    jdbcTemplate.update("update account set name = ?,money = ? where id = ?","光头强",100,7);
    }

    /**
    * 删除
    */
    @Test
    public void run3(){
    jdbcTemplate.update("delete from account where id = ?",7);
    }

    /**
    * 通过id查询
    */
    @Test
    public void run4(){
    Account account = jdbcTemplate.queryForObject("select * from account where id = ?", new BeanMapper(), 6);
    System.out.println(account);
    }

    /**
    * 查询所有的数据
    */
    @Test
    public void run5(){
    List<Account> list = jdbcTemplate.query("select * from account", new BeanMapper());
    for (Account account : list) {
    System.out.println(account);
    }
    }

    }

    /**
    * 实现类,用来进行数据封装的
    */
    class BeanMapper implements RowMapper<Account>{

    /**
    * 是一行一行进行数据封装的
    * @param resultSet
    * @param i
    * @return
    * @throws SQLException
    */
    @Override
    public Account mapRow(ResultSet resultSet, int i) throws SQLException {
    Account account = new Account();
    account.setId(resultSet.getInt("id"));
    account.setName(resultSet.getString("name"));
    account.setMoney(resultSet.getDouble("money"));
    return account;
    }

    }

    模拟转账

  • 编写service层代码
    package cn.tx.demo2;
    ​ public interface AccountService {

    /**
    * 转账的方法
    * @param out 付款人
    * @param in 收款人
    * @param money 金额
    */
    public void pay(String out,String in,double money);

    }
  • 实现接口
    package cn.tx.demo2;
    ​ public class AccountServiceImpl implements AccountService {

    private AccountDao accountDao;
    public void setAccountDao(AccountDao accountDao) {
    this.accountDao = accountDao;
    }

    /**
    * 转账方法
    * @param out 付款人
    * @param in 收款人
    * @param money 金额
    */
    @Override
    public void pay(String out, String in, double money) {
    // 调用dao方法
    accountDao.outMoney(out,money);

    accountDao.inMoney(in,money);
    }

    }
  • dao层的代码
    package cn.tx.demo2;
    ​ public interface AccountDao {

    /**
    * 付款
    * @param out
    * @param money
    */
    public void outMoney(String out,double money);

    /**
    * 收款
    * @param in
    * @param money
    */
    public void inMoney(String in,double money);

    }
  • 实现dao层的接口
    package cn.tx.demo2;

    import org.springframework.jdbc.core.JdbcTemplate;
    ​ public class AccountDaoImpl implements AccountDao {

    private JdbcTemplate jdbcTemplate;
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
    this.jdbcTemplate = jdbcTemplate;
    }

    /**
    * 付款
    * @param out
    * @param money
    */
    @Override
    public void outMoney(String out, double money) {
    jdbcTemplate.update("update account set money = money - ? where name = ?",money,out);
    }

    /**
    * 收款
    * @param in
    * @param money
    */
    @Override
    public void inMoney(String in, double money) {
    jdbcTemplate.update("update account set money = money + ? where name = ?",money,in);
    }

    }
  • 编写配置文件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"
    xmlns:aop="http://www.springframework.org/schema/aop"
    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
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--第二种写法:使用提供标签的方式-->
    <context:property-placeholder location="classpath:jdbc.properties" />

    <!--加载属性的文件-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
    <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>

    <!--配置Jdbc模板类-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    <property name="dataSource" ref="dataSource" />
    </bean>

    <!--配置service-->
    <bean id="accountService" class="cn.tx.demo2.AccountServiceImpl">
    <property name="accountDao" ref="accountDao"/>
    </bean>

    <!--配置service-->
    <bean id="accountDao" class="cn.tx.demo2.AccountDaoImpl">
    <property name="jdbcTemplate" ref="jdbcTemplate" />
    </bean>

    </beans>
  • 测试转账和收款
     package cn.tx.test;

    import cn.tx.demo2.AccountService;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    ​ @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(value = "classpath:applicationContext_dao1.xml")
    public class Demo2 {

    @Autowired
    private AccountService accountService;

    /**
    * 测试转账的方法
    */
    @Test
    public void testPay(){
    accountService.pay("熊大","熊二",100);
    }

    }

    在dao层使用JdbcDaoSupport 第二种方式,进行转账和收款的测试

  • 同样在service层实现接口
     package cn.tx.demo3;
    ​ public class AccountServiceImpl implements AccountService {

    private AccountDao accountDao;
    public void setAccountDao(AccountDao accountDao) {
    this.accountDao = accountDao;
    }

    /**
    * 转账方法
    * @param out 付款人
    * @param in 收款人
    * @param money 金额
    */
    @Override
    public void pay(String out, String in, double money) {
    // 调用dao方法
    accountDao.outMoney(out,money);

    accountDao.inMoney(in,money);
    }

    }
  • 注意在dao层编写,继承JdbcDaoSupport 和实现接口AccountDao 
     package cn.tx.demo3;

    import org.springframework.jdbc.core.JdbcTemplate;
    import org.springframework.jdbc.core.support.JdbcDaoSupport;
    ​ public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao {

    /**
    * 付款
    * @param out
    * @param money
    */
    @Override
    public void outMoney(String out, double money) {
    this.getJdbcTemplate().update("update account set money = money - ? where name = ?",money,out);
    }

    /**
    * 收款
    * @param in
    * @param money
    */
    @Override
    public void inMoney(String in, double money) {
    this.getJdbcTemplate().update("update account set money = money + ? where name = ?",money,in);
    }

    }
  • 编写配置文件
    <?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"
    xmlns:aop="http://www.springframework.org/schema/aop"
    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
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--第二种写法:使用提供标签的方式-->
    <context:property-placeholder location="classpath:jdbc.properties" />

    <!--加载属性的文件-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
    <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>

    <!--配置Jdbc模板类
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    <property name="dataSource" ref="dataSource" />
    </bean>
    -->

    <!--配置service-->
    <bean id="accountService" class="cn.tx.demo3.AccountServiceImpl">
    <property name="accountDao" ref="accountDao"/>
    </bean>

    <!--配置dao
    <bean id="accountDao" class="cn.tx.demo3.AccountDaoImpl">
    <property name="jdbcTemplate" ref="jdbcTemplate" />
    </bean>
    -->

    <bean id="accountDao" class="cn.tx.demo3.AccountDaoImpl">
    <property name="dataSource" ref="dataSource" />
    </bean>

    </beans>
  • 测试使用JdbcDaoSupport 的方法进行转账和收款的测试
     package cn.tx.test;

    import cn.tx.demo3.AccountService;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    ​ @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(value = "classpath:applicationContext_dao2.xml")
    public class Demo3 {

    @Autowired
    private AccountService accountService;

    /**
    * 测试转账的方法
    */
    @Test
    public void testPay(){
    accountService.pay("熊大","熊二",100);
    }

    }

解析Spring第四天(Spring中的事物、Spring框架来管理模板类)的更多相关文章

  1. 使用Spring框架来管理模板类

    1. 刚才编写的代码使用的是new的方式,应该把这些类交给Spring框架来管理. 2. 修改的步骤如下 applicationContext.xml中<beans>标签的开头配置为: * ...

  2. Spring框架的JDBC模板技术和事物

    Spring框架的JDBC模板技术         技术分析之Spring框架的JDBC模板技术概述  1. Spring框架中提供了很多持久层的模板类来简化编程,使用模板类编写程序会变的简单     ...

  3. Spring中的JDBC模板类入门

    1.Spring框架中提供了很多持久层的模板类来简化编程,使用模板类编写程序会变的简单 2.提供了JDBC模板,Spring框架提供的 *JdbcTemplate类 3.Spring框架可以整合Hib ...

  4. Spring框架的JDBC模板技术概述

    1. Spring框架中提供了很多持久层的模板类来简化编程,使用模板类编写程序会变的简单 2. 提供了JDBC模板,Spring框架提供的 * JdbcTemplate类 3. Spring框架可以整 ...

  5. 演示Spring框架的JDBC模板的简单操作

    1. 步骤一:创建数据库的表结构 create database spring_day03; use spring_day03; create table t_account( id int prim ...

  6. python框架Django中MTV框架之Template(模板/界面)

    MTV框架之Template(模板/界面) 关注公众号"轻松学编程"了解更多. 1.模板目录位置 应用下 不需要注册 无法跨应用地进行复用 工程下 需要注册 settings.py ...

  7. spring学习四:Spring中的后置处理器BeanPostProcessor

    BeanPostProcessor接口作用: 如果我们想在Spring容器中完成bean实例化.配置以及其他初始化方法前后要添加一些自己逻辑处理.我们需要定义一个或多个BeanPostProcesso ...

  8. 【Spring】关于Boot应用中集成Spring Security你必须了解的那些事

    Spring Security Spring Security是Spring社区的一个顶级项目,也是Spring Boot官方推荐使用的Security框架.除了常规的Authentication和A ...

  9. Spring AOP四种实现方式Demo详解与相关知识探究

    一.前言 在网络上看到一篇博客Spring实现AOP的4种方式,博主写的很通俗易懂,但排版实在抓狂,对于我这么一个对排版.代码格式有强迫症的人来说,实在是不能忍受~~~~(>_<)~~~~ ...

随机推荐

  1. 同域SQL server 做镜像服务器遇到1418错误

    今天遇到了如题所说的错误,查了一天没有看到好的解决方案,因为作者是小白,所以对于解决方案都是代码的那种,完全理解不了. 现在,讲述一下我的解决方法.因为是同域的服务器,这个时候说网络访问不了对方,但是 ...

  2. 【JDK1.8】Java HashMap实现细节

    底层是用数组实现的 /** * The table, initialized on first use, and resized as * necessary. When allocated, len ...

  3. Async Clipboard AP

    转自奇舞周刊,个人学习记录,侵权删 编者按:本文作者李松峰,资深技术图书译者,翻译出版过40余部技术及交互设计专著,现任360奇舞团高级前端开发工程师,360前端技术委员会委员.W3C AC代表 如果 ...

  4. JAVA实现生产消费者模型

    前言 最近面试比较多,发现生产消费者模型在各公司面试的过程中问的还是比较多的,记录一下常见JAVA实现生产者消费模型的代码 思路 我们通过三种模式来实现 通过wait和notify 通过Lock和Co ...

  5. classmethod和staticmethod

    假设有这么一个 class class Date(object): def __init__(self, day=0, month=0, year=0): self.day = day self.mo ...

  6. Delphi 文件操作(路径、目录)

    Delphi利用系统环境变量获取常用系统目录 //譬如 %WINDIR% 是表示系统目录的系统变量, 可以这样获取: var s: string; begin s := GetEnvironmentV ...

  7. TFS——更改计算机名称,影响TFS使用

    今天把自己电脑的计算机名称改了,打开VS的时候,就提示以下的错误: 报错情况 显示错误:工作区 DADI--20141015Q;SD-SERVER\Administrator 未驻留在此计算机上.如果 ...

  8. div + css 边框 虚线

    div + css 边框 虚线 dotted:[点线|有点的|点线式边框|点虚线] .introduce { border:1px dotted gray; margin:8px 5px 8px 10 ...

  9. 1. USB协议

    1.1 Packets USB总线上数据传输以包为基本单位,一个包含不同的域,但都要从同步域开始,然后跟踪一个包标识符PID(Packet Identifier),最终以包结束符EOP(End of ...

  10. ISA虚拟化的条件

    ISA(Instruction Set Architecture) 指令集体系结构,是硬件与软件层之间的接口. 本地系统虚拟机 本地系统虚拟机,就是Bare-Metal虚拟机,直接运行在硬件上,在它上 ...