解析Spring第四天(Spring中的事物、Spring框架来管理模板类)

  • JDBC模板技术:

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

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

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

    • JdbcTemplate类,Connection 表示连接,管理事务 Statement ResultSet
  • 如何使用JDBC模板类?
  • 在数据库中新增表结构和数据
     1 DROP TABLE IF EXISTS `account`;
     2 CREATE TABLE `account` (
     3   `id` int(11) NOT NULL AUTO_INCREMENT,
     4   `name` varchar(40) DEFAULT NULL,
     5   `money` double DEFAULT NULL,
     6   PRIMARY KEY (`id`)
     7 ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
     8 
     9 -- ----------------------------
    10 -- Records of account
    11 -- ----------------------------
    12 INSERT INTO `account` VALUES ('1', 'aaa', '1000');
    13 INSERT INTO `account` VALUES ('2', 'bbb', '1000');
    14 INSERT INTO `account` VALUES ('3', 'ccc', '1000');
    15 INSERT INTO `account` VALUES ('4', '熊大', '700');
    16 INSERT INTO `account` VALUES ('5', '熊二', '1200');
    17 INSERT INTO `account` VALUES ('6', '熊三', '800');

     

  • 创建一个普通的Maven工程,引入坐标
 1 <dependencies>
 2     <dependency>
 3         <groupId>org.springframework</groupId>
 4         <artifactId>spring-context</artifactId>
 5         <version>5.0.2.RELEASE</version>
 6     </dependency>
 7     <dependency>
 8         <groupId>commons-logging</groupId>
 9         <artifactId>commons-logging</artifactId>
10         <version>1.2</version>
11     </dependency>
12     <dependency>
13         <groupId>log4j</groupId>
14         <artifactId>log4j</artifactId>
15         <version>1.2.12</version>
16     </dependency>
17     <dependency>
18         <groupId>junit</groupId>
19         <artifactId>junit</artifactId>
20         <version>4.12</version>
21     </dependency>
22     <dependency>
23         <groupId>org.springframework</groupId>
24         <artifactId>spring-test</artifactId>
25         <version>5.0.2.RELEASE</version>
26     </dependency>
27     
28     <dependency>
29         <groupId>aopalliance</groupId>
30         <artifactId>aopalliance</artifactId>
31         <version>1.0</version>
32     </dependency>
33     <dependency>
34         <groupId>org.springframework</groupId>
35         <artifactId>spring-aspects</artifactId>
36         <version>5.0.2.RELEASE</version>
37     </dependency>
38     <dependency>
39         <groupId>org.aspectj</groupId>
40         <artifactId>aspectjweaver</artifactId>
41         <version>1.8.13</version>
42     </dependency>
43     <dependency>
44         <groupId>mysql</groupId>
45         <artifactId>mysql-connector-java</artifactId>
46         <version>5.1.6</version>
47     </dependency>
48     <dependency>
49         <groupId>org.springframework</groupId>
50         <artifactId>spring-jdbc</artifactId>
51         <version>5.0.2.RELEASE</version>
52     </dependency>
53     <dependency>
54         <groupId>org.springframework</groupId>
55         <artifactId>spring-tx</artifactId>
56         <version>5.0.2.RELEASE</version>
57     </dependency>
58   </dependencies>
  • 使用Spring框架来管理模板类,Spring管理内置的连接池
     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"
     4        xmlns:context="http://www.springframework.org/schema/context"
     5        xmlns:aop="http://www.springframework.org/schema/aop"
     6        xsi:schemaLocation="
     7                 http://www.springframework.org/schema/beans
     8                 http://www.springframework.org/schema/beans/spring-beans.xsd
     9                 http://www.springframework.org/schema/context
    10                 http://www.springframework.org/schema/context/spring-context.xsd
    11                 http://www.springframework.org/schema/aop
    12                 http://www.springframework.org/schema/aop/spring-aop.xsd">
    13 14     <!--配置连接池-->
    15     <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    16         <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    17         <property name="url" value="jdbc:mysql:///spring_db" />
    18         <property name="username" value="root" />
    19         <property name="password" value="root" />
    20     </bean>
    21 22     <!--配置jdbc模板-->
    23     <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    24         <property name="dataSource" ref="dataSource" />
    25     </bean>
    26 27 </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。配置连接数据库的基本信息
    1 jdbc.driverClassName=com.mysql.jdbc.Driver
    2     jdbc.url=jdbc:mysql:///spring_db
    3     jdbc.username=root
    4     jdbc.password=root
  • 在xml的文件中配置读取属性文件,连接数据库和配置jdbc模板
     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"
     4        xmlns:context="http://www.springframework.org/schema/context"
     5        xmlns:aop="http://www.springframework.org/schema/aop"
     6        xsi:schemaLocation="
     7                 http://www.springframework.org/schema/beans
     8                 http://www.springframework.org/schema/beans/spring-beans.xsd
     9                 http://www.springframework.org/schema/context
    10                 http://www.springframework.org/schema/context/spring-context.xsd
    11                 http://www.springframework.org/schema/aop
    12                 http://www.springframework.org/schema/aop/spring-aop.xsd">
    13 14     <!--配置连接池,使用的是Spring框架内置的连接池
    15     <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    16         <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    17         <property name="url" value="jdbc:mysql:///spring_db" />
    18         <property name="username" value="root" />
    19         <property name="password" value="root" />
    20     </bean>
    21     -->
    22 23     <!--使用开源连接池
    24     <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
    25         <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    26         <property name="url" value="jdbc:mysql:///spring_db" />
    27         <property name="username" value="root" />
    28         <property name="password" value="root" />
    29     </bean>
    30     -->
    31 32     <!--加载属性文件
    33     <bean id="placeholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    34         <property name="location" value="classpath:jdbc.properties" />
    35     </bean>
    36     -->
    37 38     <!--第二种写法:使用提供标签的方式-->
    39     <context:property-placeholder location="classpath:jdbc.properties" />
    40 41     <!--加载属性的文件-->
    42     <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
    43         <property name="driverClassName" value="${jdbc.driverClassName}" />
    44         <property name="url" value="${jdbc.url}" />
    45         <property name="username" value="${jdbc.username}" />
    46         <property name="password" value="${jdbc.password}" />
    47     </bean>
    48 49     <!--配置jdbc模板-->
    50     <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    51         <property name="dataSource" ref="dataSource" />
    52     </bean>
    53 54 </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>
  • 测试转账和收款
     1 package cn.tx.test;
     2  3 import cn.tx.demo2.AccountService;
     4 import org.junit.Test;
     5 import org.junit.runner.RunWith;
     6 import org.springframework.beans.factory.annotation.Autowired;
     7 import org.springframework.test.context.ContextConfiguration;
     8 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
     9 10 
    11 
    12 @RunWith(SpringJUnit4ClassRunner.class)
    13 @ContextConfiguration(value = "classpath:applicationContext_dao1.xml")
    14 public class Demo2 {
    15 16     @Autowired
    17     private AccountService accountService;
    18 19     /**
    20      * 测试转账的方法
    21      */
    22     @Test
    23     public void testPay(){
    24         accountService.pay("熊大","熊二",100);
    25     }
    26 27 }

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

  • 同样在service层实现接口
     1  
     2 package cn.tx.demo3;
     3  4 
     5 public class AccountServiceImpl implements AccountService {
     6  7     private AccountDao accountDao;
     8     public void setAccountDao(AccountDao accountDao) {
     9         this.accountDao = accountDao;
    10     }
    11 12     /**
    13      * 转账方法
    14      * @param out       付款人
    15      * @param in        收款人
    16      * @param money     金额
    17      */
    18     @Override
    19     public void pay(String out, String in, double money) {
    20         // 调用dao方法
    21         accountDao.outMoney(out,money);
    22 23         accountDao.inMoney(in,money);
    24     }
    25 26 }

     

  • 注意在dao层编写,继承JdbcDaoSupport 和实现接口AccountDao 
     1 package cn.tx.demo3;
     2  3 import org.springframework.jdbc.core.JdbcTemplate;
     4 import org.springframework.jdbc.core.support.JdbcDaoSupport;
     5  6 
     7 public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao {
     8  9     /**
    10      * 付款
    11      * @param out
    12      * @param money
    13      */
    14     @Override
    15     public void outMoney(String out, double money) {
    16         this.getJdbcTemplate().update("update account set money = money - ? where name = ?",money,out);
    17     }
    18 19     /**
    20      * 收款
    21      * @param in
    22      * @param money
    23      */
    24     @Override
    25     public void inMoney(String in, double money) {
    26         this.getJdbcTemplate().update("update account set money = money + ? where name = ?",money,in);
    27     }
    28 29 }
    30

     

  • 编写配置文件
    <?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 的方法进行转账和收款的测试
     1 package cn.tx.test;
     2  3 import cn.tx.demo3.AccountService;
     4 import org.junit.Test;
     5 import org.junit.runner.RunWith;
     6 import org.springframework.beans.factory.annotation.Autowired;
     7 import org.springframework.test.context.ContextConfiguration;
     8 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
     9 10 
    11 @RunWith(SpringJUnit4ClassRunner.class)
    12 @ContextConfiguration(value = "classpath:applicationContext_dao2.xml")
    13 public class Demo3 {
    14 15     @Autowired
    16     private AccountService accountService;
    17 18     /**
    19      * 测试转账的方法
    20      */
    21     @Test
    22     public void testPay(){
    23         accountService.pay("熊大","熊二",100);
    24     }
    25 26 }
    27

     

posted @ 2019-10-29 01:06  白天黑天阴天  阅读(178)  评论(0编辑  收藏  举报