欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SSH框架之Spring第四篇

程序员文章站 2022-07-09 20:34:08
1.1 JdbcTemplate概述 : 它是spring框架中提供的一个对象,是对原始JdbcAPI对象的简单封装.spring框架为我们提供了很多的操作模板类. ORM持久化技术 模板类 JDBC org.springframework.jdbc.core.J... ......
1.1 jdbctemplate概述 : 
        它是spring框架中提供的一个对象,是对原始jdbcapi对象的简单封装.spring框架为我们提供了很多的操作模板类.
        orm持久化技术                        模板类
        jdbc                    org.springframework.jdbc.core.jdbctemplate.
        hibernate3.0             org.springframework.orm.hibernate3.hibernatetemplate.
        ibatis(mybatis)            org.springframework.orm.ibatis.sqlmapclienttemplate.
        jpa                        org.springframework.orm.jpa.jpatemplate.
    在导包的时候需要导入spring-jdbc-4.24.releasf.jar,还需要导入一个spring-tx-4.2.4.release.jar(它和事务有关)

    <!-- 配置数据源 -->
        <bean id="datasource" class="org.apache.commons.dbcp.basicdatasource">
            <property name="driverclassname" value="com.mysql.jdbc.driver"></property>
            <property name="url" value="jdbc:mysql:// /spring_day04"></property>
            <property name="username" value="root"></property>
            <property name="password" value="1234"></property>
        </bean>
    1.3.3.3配置spring内置数据源
        spring框架也提供了一个内置数据源,我们也可以使用spring的内置数据源,它就在spring-jdbc-4.2.4.reease.jar包中:
        <bean id="datasource" class="org.springframework.jdbc.datasource.drivermanagerdatasource">
            <property name="driverclassname" value="com.mysql.jdbc.driver"></property>
            <property name="url" value="jdbc:mysql:///spring_day04"></property>
            <property name="username" value="root"></property>
            <property name="password" value="1234"></property>
        </bean>
    1.3.4将数据库连接的信息配置到属性文件中:
        【定义属性文件】
        jdbc.driverclass=com.mysql.jdbc.driver
        jdbc.url=jdbc:mysql:///spring_day02
        jdbc.username=root
        jdbc.password=123
        【引入外部的属性文件】
        一种方式:
            <!-- 引入外部属性文件: -->
            <bean class="org.springframework.beans.factory.config.propertyplaceholderconfigurer">
                <property name="location" value="classpath:jdbc.properties"/>
            </bean>

        二种方式:
        <context:property-placeholder location="classpath:jdbc.properties"/>

    1.4jdbctemplate的增删改查操作
        1.4.1前期准备
        创建数据库:
        create database spring_day04;
        use spring_day04;
        创建表:
        create table account(
            id int primary key auto_increment,
            name varchar(40),
            money float
        )character set utf8 collate utf8_general_ci;
    1.4.2在spring配置文件中配置jdbctemplate
        <?xml version="1.0" encoding="utf-8"?>
        <beans xmlns="http://www.springframework.org/schema/beans"
                xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
                xsi:schemalocation="http://www.springframework.org/schema/beans 
                http://www.springframework.org/schema/beans/spring-beans.xsd">

            <!-- 配置一个数据库的操作模板:jdbctemplate -->
            <bean id="jdbctemplate" class="org.springframework.jdbc.core.jdbctemplate">
                <property name="datasource" ref="datasource"></property>
            </bean>
            
            <!-- 配置数据源 -->
            <bean id="datasource" class="org.springframework.jdbc.datasource.drivermanagerdatasource">
            <property name="driverclassname" value="com.mysql.jdbc.driver"></property>
            <property name="url" value="jdbc:mysql:///spring_day04"></property>
            <property name="username" value="root"></property>
            <property name="password" value="1234"></property>
        </bean>
        </beans>
    1.4.3最基本使用
        public class jdbctemplatedemo2 {
            public static void main(string[] args) {
                //1.获取spring容器
                applicationcontext ac = new classpathxmlapplicationcontext("bean.xml");
                //2.根据id获取bean对象
                jdbctemplate jt = (jdbctemplate) ac.getbean("jdbctemplate");
                //3.执行操作
                jt.execute("insert into account(name,money)values('eee',500)");
            }
        }
    1.4.4保存操作
        public class jdbctemplatedemo3 {
            public static void main(string[] args) {

                //1.获取spring容器
                applicationcontext ac = new classpathxmlapplicationcontext("bean.xml");
                //2.根据id获取bean对象
                jdbctemplate jt = (jdbctemplate) ac.getbean("jdbctemplate");
                //3.执行操作
                //保存
                jt.update("insert into account(name,money)values(?,?)","fff",5000);
            }
        }
    1.4.5更新操作
        public class jdbctemplatedemo3 {
            public static void main(string[] args) {

                //1.获取spring容器
                applicationcontext ac = new classpathxmlapplicationcontext("bean.xml");
                //2.根据id获取bean对象
                jdbctemplate jt = (jdbctemplate) ac.getbean("jdbctemplate");
                //3.执行操作
                //修改
                jt.update("update account set money = money-? where id = ?",300,6);
            }
        }
    1.4.6删除操作
        public class jdbctemplatedemo3 {
            public static void main(string[] args) {

                //1.获取spring容器
                applicationcontext ac = new classpathxmlapplicationcontext("bean.xml");
                //2.根据id获取bean对象
                jdbctemplate jt = (jdbctemplate) ac.getbean("jdbctemplate");
                //3.执行操作
                //删除
                jt.update("delete from account where id = ?",6);
            }
        }
    1.4.7查询所有操作
        public class jdbctemplatedemo3 {
            public static void main(string[] args) {

                //1.获取spring容器
                applicationcontext ac = new classpathxmlapplicationcontext("bean.xml");
                //2.根据id获取bean对象
                jdbctemplate jt = (jdbctemplate) ac.getbean("jdbctemplate");
                //3.执行操作
                //查询所有
                list<account> accounts = jt.query("select * from account where money > ? ", 
                                                    new accountrowmapper(), 500);
                for(account o : accounts){
                    system.out.println(o);
                }
            }
        }

        public class accountrowmapper implements rowmapper<account>{
            @override
            public account maprow(resultset rs, int rownum) throws sqlexception {
                account account = new account();
                account.setid(rs.getint("id"));
                account.setname(rs.getstring("name"));
                account.setmoney(rs.getfloat("money"));
                return account;
            }
            
        }

    1.4.8查询一个操作
        使用rowmapper的方式:常用的方式
        public class jdbctemplatedemo3 {
            public static void main(string[] args) {

                //1.获取spring容器
                applicationcontext ac = new classpathxmlapplicationcontext("bean.xml");
                //2.根据id获取bean对象
                jdbctemplate jt = (jdbctemplate) ac.getbean("jdbctemplate");
                //3.执行操作
                //查询一个
                list<account> as = jt.query("select * from account where id = ? ", 
                                                new accountrowmapper(), 55);
                system.out.println(as.isempty()?"没有结果":as.get(0));
            }
        }
    1.4.9查询返回一行一列操作
        public class jdbctemplatedemo3 {
            public static void main(string[] args) {

                //1.获取spring容器
                applicationcontext ac = new classpathxmlapplicationcontext("bean.xml");
                //2.根据id获取bean对象
                jdbctemplate jt = (jdbctemplate) ac.getbean("jdbctemplate");
                //3.执行操作
                //查询返回一行一列:使用聚合函数,在不使用group by字句时,都是返回一行一列。最长用的就是分页中获取总记录条数
                integer total = jt.queryforobject("select count(*) from account where money > ? ",integer.class,500);
                system.out.println(total);
            }
        }
applicationcontext.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"
            xmlns:tx="http://www.springframework.org/schema/tx"
            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
            http://www.springframework.org/schema/tx 
            http://www.springframework.org/schema/tx/spring-tx.xsd">

            <!-- 使用spring管理连接池对象,spring内置的连接池对象 -->
            
            <!-- <bean id="datasource" class="org.springframework.jdbc.datasource.drivermanagerdatasource">
                <property name="driverclassname" value="com.mysql.jdbc.driver"></property>
                <property name="url" value="jdbc:mysql:///spring_04"/>
                <property name="username" value="root"></property>
                <property name="password" value="root"></property>
            </bean> -->
            
            <!-- 配置数据源,使用spring整合dbcp连接,没有导入jar包 -->
            <!-- <bean id="datasource" class="org.apache.tomcat.dbcp.dbcp.basicdatasource">
                <property name="driverclassname" value="com.mysql.jdbc.driver"/>
                <property name="url" value="jdbc:mysql:///spring_04"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </bean> -->
            
            <!-- 使用spring整合c3p0的连接池,没有采用属性文件的方式 -->
            <!-- 
            <bean id="datasource" class="com.mchange.v2.c3p0.combopooleddatasource">
                <property name="driverclass" value="com.mysql.jdbc.driver"/>
                <property name="jdbcurl" value="jdbc:mysql:///spring_04"/>
                <property name="user" value="root"/>
                <property name="password" value="root"/>
            </bean> -->
            
            <!-- 使用context:property-placeholder标签,读取属性文件 -->
            <context:property-placeholder location="classpath:db.properties"/>
            
            <!-- 使用spring整合c3p0的连接池,采用属性文件的方式 -->
            <bean id="datasource" class="com.mchange.v2.c3p0.combopooleddatasource">
                <property name="driverclass" value="${jdbc.driver}"/>
                <property name="jdbcurl" value="${jdbc.url}"/>
                <property name="user" value="${jdbc.user}"/>
                <property name="password" value="${jdbc.password}"/>
                
            </bean>
            <!-- spring管理jbdctemplate模板 -->
            <bean id="jdbctemplate" class="org.springframework.jdbc.core.jdbctemplate">
                <property name="datasource" ref="datasource"/>
            </bean>

        </beans>
db.properties : 属性文件
        jdbc.driver=com.mysql.jdbc.driver
        jdbc.url=jdbc:mysql:///spring_day04
        jdbc.user=root
        jdbc.password=root
demo测试 :
    package com.ithiema.demo1;

    import java.sql.resultset;
    import java.sql.sqlexception;
    import java.util.list;

    import javax.annotation.resource;

    import org.junit.test;
    import org.junit.runner.runwith;
    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;

    /**
     * spring整合jdbctemplate的方式入门
     * @author administrator
     */
    @runwith(springjunit4classrunner.class)
    @contextconfiguration("classpath:applicationcontext.xml")
    public class demo11 {
        
        @resource(name="jdbctemplate")
        private jdbctemplate jdbctemplate;
        
        /**
         * 添加
         */
        @test
        public void run1(){
            jdbctemplate.update("insert into account values (null,?,?)", "嘿嘿",10000);
        }
        
        /**
         * 修改
         */
        @test
        public void run2(){
            jdbctemplate.update("update account set name = ?,money = ? where id = ?", "嘻嘻",5000,6);
        }
        
        /**
         * 删除
         */
        @test
        public void run3(){
            jdbctemplate.update("delete from account where id = ?", 6);
        }
        
        /**
         * 查询多条数据
         */
        @test
        public void run4(){
            // sql          sql语句
            // rowmapper    提供封装数据的接口,自己提供实现类(自己封装数据的)
            list<account> list = jdbctemplate.query("select * from account", new beanmapper());
            for (account account : list) {
                system.out.println(account);
            }
        }    
    }

    /**
     * 自己封装的实现类,封装数据的
     * @author administrator
     */
    class beanmapper implements rowmapper<account>{
        
        /**
         * 一行一行封装数据的
         */
        public account maprow(resultset rs, int index) throws sqlexception {
            // 创建account对象,一个属性一个属性赋值,返回对象
            account ac = new account();
            ac.setid(rs.getint("id"));
            ac.setname(rs.getstring("name"));
            ac.setmoney(rs.getdouble("money"));
            return ac;
        }
        
    }

2,1 spring 事务控制我们要明确的
    1: javaee体系进行分层开发,事务处理位于业务层,spring提供了分层设计业务层的事务处理解决方案.
    2: spring框架为我们提供就一组事务控制的接口.这组接口是在spring-tx-4.2.4release.jar中.
    3: spring的事务都是基于aop的,它既可以使用编程的方式实现,也可以使用配置的方式实现
    2.2spring中事务控制的api介绍
        2.2.1platformtransactionmanager
        此接口是spring的事务管理器,它里面提供了我们常用的操作事务的方法,如下图:

        我们在开发中都是使用它的实现类,如下图:

        真正管理事务的对象
        org.springframework.jdbc.datasource.datasourcetransactionmanager    使用spring jdbc或ibatis 进行持久化数据时使用
        org.springframework.orm.hibernate3.hibernatetransactionmanager        使用hibernate版本进行持久化数据时使用
    2.2.2transactiondefinition
        它是事务的定义信息对象,里面有如下方法:

    2.2.2.1事务的隔离级别

    2.2.2.2事务的传播行为
        required:如果当前没有事务,就新建一个事务,如果已经存在一个事务中,加入到这个事务中。一般的选择(默认值)
        supports:支持当前事务,如果当前没有事务,就以非事务方式执行(没有事务)
        mandatory:使用当前的事务,如果当前没有事务,就抛出异常
        requers_new:新建事务,如果当前在事务中,把当前事务挂起。
        not_supported:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起
        never:以非事务方式运行,如果当前存在事务,抛出异常
        nested:如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行required类似的操作。
        2.2.2.3超时时间
        默认值是-1,没有超时限制。如果有,以秒为单位进行设置。
        2.2.2.4是否是只读事务
        建议查询时设置为只读。
        2.2.3transactionstatus
        此接口提供的是事务具体的运行状态,方法介绍如下图:

    2.3基于xml的声明式事务控制(配置方式)重点
        2.3.1环境搭建
        2.3.1.1第一步:拷贝必要的jar包到工程的lib目录

    2.3.1.2第二步:创建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:aop="http://www.springframework.org/schema/aop"
             xmlns:tx="http://www.springframework.org/schema/tx"
                xsi:schemalocation="http://www.springframework.org/schema/beans 
                        http://www.springframework.org/schema/beans/spring-beans.xsd
                        http://www.springframework.org/schema/tx 
                        http://www.springframework.org/schema/tx/spring-tx.xsd
                        http://www.springframework.org/schema/aop 
                        http://www.springframework.org/schema/aop/spring-aop.xsd">    
        </beans>
        2.3.1.3第三步:准备数据库表和实体类
        创建数据库:
        create database spring_day04;
        use spring_day04;
        创建表:
        create table account(
            id int primary key auto_increment,
            name varchar(40),
            money float
        )character set utf8 collate utf8_general_ci;
        /**
         * 账户的实体
         */
        public class account implements serializable {

            private integer id;
            private string name;
            private float money;
            public integer getid() {
                return id;
            }
            public void setid(integer id) {
                this.id = id;
            }
            public string getname() {
                return name;
            }
            public void setname(string name) {
                this.name = name;
            }
            public float getmoney() {
                return money;
            }
            public void setmoney(float money) {
                this.money = money;
            }
            @override
            public string tostring() {
                return "account [id=" + id + ", name=" + name + ", money=" + money + "]";
            }
        }
        2.3.1.4第四步:编写业务层接口和实现类
        /**
         * 账户的业务层接口
         */
        public interface iaccountservice {
            
            /**
             * 根据id查询账户信息
             * @param id
             * @return
             */
            account findaccountbyid(integer id);//查
            
            /**
             * 转账
             * @param sourcename    转出账户名称
             * @param targename        转入账户名称
             * @param money            转账金额
             */
            void transfer(string sourcename,string targename,float money);//增删改
        }

        /**
         * 账户的业务层实现类
         */
        public class accountserviceimpl implements iaccountservice {
            
            private iaccountdao accountdao;
            
            public void setaccountdao(iaccountdao accountdao) {
                this.accountdao = accountdao;
            }

            @override
            public account findaccountbyid(integer id) {
                return accountdao.findaccountbyid(id);
            }

            @override
            public void transfer(string sourcename, string targename, float money) {
                //1.根据名称查询两个账户
                account source = accountdao.findaccountbyname(sourcename);
                account target = accountdao.findaccountbyname(targename);
                //2.修改两个账户的金额
                source.setmoney(source.getmoney()-money);//转出账户减钱
                target.setmoney(target.getmoney()+money);//转入账户加钱
                //3.更新两个账户
                accountdao.updateaccount(source);
                int i=1/0;
                accountdao.updateaccount(target);
            }
        }
        2.3.1.5第五步:编写dao接口和实现类
        /**
         * 账户的持久层接口
         */
        public interface iaccountdao {
            
            /**
             * 根据id查询账户信息
             * @param id
             * @return
             */
            account findaccountbyid(integer id);

            /**
             * 根据名称查询账户信息
             * @return
             */
            account findaccountbyname(string name);
            
            /**
             * 更新账户信息
             * @param account
             */
            void updateaccount(account account);
        }
        /**
         * 账户的持久层实现类
         * 此版本dao,只需要给它的父类注入一个数据源
         */
        public class accountdaoimpl extends jdbcdaosupport implements iaccountdao {

            @override
            public account findaccountbyid(integer id) {
                list<account> list = getjdbctemplate().query("select * from account where id = ? ",new accountrowmapper(),id);
                return list.isempty()?null:list.get(0);
            }

            @override
            public account findaccountbyname(string name) {
                list<account> list =  getjdbctemplate().query("select * from account where name = ? ",new accountrowmapper(),name);
                if(list.isempty()){
                    return null;
                }
                if(list.size()>1){
                    throw new runtimeexception("结果集不唯一,不是只有一个账户对象");
                }
                return list.get(0);
            }

            @override
            public void updateaccount(account account) {
                getjdbctemplate().update("update account set money = ? where id = ? ",account.getmoney(),account.getid());
            }
        }

        /**
         * 账户的封装类rowmapper的实现类
         */
        public class accountrowmapper implements rowmapper<account>{

            @override
            public account maprow(resultset rs, int rownum) throws sqlexception {
                account account = new account();
                account.setid(rs.getint("id"));
                account.setname(rs.getstring("name"));
                account.setmoney(rs.getfloat("money"));
                return account;
            }
        }
        2.3.1.6第六步:在配置文件中配置业务层和持久层对
        <!-- 配置service -->
        <bean id="accountservice" class="com.baidu.service.impl.accountserviceimpl">
            <property name="accountdao" ref="accountdao"></property>
        </bean>
            
        <!-- 配置dao -->
        <bean id="accountdao" class="com.baidu.dao.impl.accountdaoimpl">
            <!-- 注入datasource -->
            <property name="datasource" ref="datasource"></property>
        </bean>
            
        <!-- 配置数据源 -->
        <bean id="datasource" class="org.springframework.jdbc.datasource.drivermanagerdatasource">
            <property name="driverclassname" value="com.mysql.jdbc.driver"></property>
            <property name="url" value="jdbc:mysql:///spring_day04"></property>
            <property name="username" value="root"></property>
            <property name="password" value="1234"></property>
        </bean>
    2.3.2配置步骤
        2.3.2.1第一步:配置事务管理器
        <!-- 配置一个事务管理器 -->
        <bean id="transactionmanager" class="org.springframework.jdbc.datasource.datasourcetransactionmanager">
            <!-- 注入datasource -->
            <property name="datasource" ref="datasource"></property>
        </bean>
        2.3.2.2第二步:配置事务的通知引用事务管理器
        <!-- 事务的配置 -->
        <tx:advice id="txadvice" transaction-manager="transactionmanager">
        </tx:advice>
        2.3.2.3第三步:配置事务的属性
        <!--在tx:advice标签内部 配置事务的属性 -->
        <tx:attributes>
        <!-- 指定方法名称:是业务核心方法 
            read-only:是否是只读事务。默认false,不只读。
            isolation:指定事务的隔离级别。默认值是使用数据库的默认隔离级别。 
            propagation:指定事务的传播行为。
            timeout:指定超时时间。默认值为:-1。永不超时。
            rollback-for:用于指定一个异常,当执行产生该异常时,事务回滚。产生其他异常,事务不回滚。没有默认值,任何异常都回滚。
            no-rollback-for:用于指定一个异常,当产生该异常时,事务不回滚,产生其他异常时,事务回滚。没有默认值,任何异常都回滚。
            -->
            <tx:method name="*" read-only="false" propagation="required"/>
            <tx:method name="find*" read-only="true" propagation="supports"/>
        </tx:attributes>
        2.3.2.4第四步:配置aop-切入点表达式
        <!-- 配置aop -->
        <aop:config>
            <!-- 配置切入点表达式 -->
            <aop:pointcut expression="execution(* com.baidu.service.impl.*.*(..))" id="pt1"/>
        </aop:config>
        2.3.2.5第五步:配置切入点表达式和事务通知的对应关系
        <!-- 在aop:config标签内部:建立事务的通知和切入点表达式的关系 -->
        <aop:advisor advice-ref="txadvice" pointcut-ref="pt1"/>
        2.4基于xml和注解组合使用的整合方式
        2.4.1环境搭建
        2.4.1.1第一步:拷贝必备的jar包到工程的lib目录

        2.4.1.2第二步:创建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:aop="http://www.springframework.org/schema/aop"
                    xmlns:tx="http://www.springframework.org/schema/tx"
                    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/tx 
                            http://www.springframework.org/schema/tx/spring-tx.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">
            <!-- 配置spring要扫描的包 -->
            <context:component-scan base-package="com.baidu"></context:component-scan>
        </beans>
    2.4.1.3第三步:创建数据库表和实体类
        和基于xml的配置相同。
        2.4.1.4第四步:创建业务层接口和实现类并使用注解让spring管理
        业务层接口和基于xml配置的时候相同。略

        /**
         * 账户的业务层实现类
         */
        @service("accountservice")
        public class accountserviceimpl implements iaccountservice {
            @autowired
            private iaccountdao accountdao;

            @override
            public account findaccountbyid(integer id) {
                return accountdao.findaccountbyid(id);
            }

            @override
            public void transfer(string sourcename, string targename, float money) {
                //1.根据名称查询两个账户
                account source = accountdao.findaccountbyname(sourcename);
                account target = accountdao.findaccountbyname(targename);
                //2.修改两个账户的金额
                source.setmoney(source.getmoney()-money);//转出账户减钱
                target.setmoney(target.getmoney()+money);//转入账户加钱
                //3.更新两个账户
                accountdao.updateaccount(source);
                int i=1/0;
                accountdao.updateaccount(target);
            }
        }
    2.4.1.5第五步:创建dao接口和实现类并使用注解让spring管理
        dao层接口和accountrowmapper与基于xml配置的时候相同。略

        @repository("accountdao")
        public class accountdaoimpl implements iaccountdao {

            @autowired
            private jdbctemplate jdbctemplate;
            
            @override
            public account findaccountbyid(integer id) {
                list<account> list = jdbctemplate.query("select * from account where id = ? ",new accountrowmapper(),id);
                return list.isempty()?null:list.get(0);
            }

            @override
            public account findaccountbyname(string name) {
                list<account> list =  jdbctemplate.query("select * from account where name = ? ",new accountrowmapper(),name);
                if(list.isempty()){
                    return null;
                }
                if(list.size()>1){
                    throw new runtimeexception("结果集不唯一,不是只有一个账户对象");
                }
                return list.get(0);
            }

            @override
            public void updateaccount(account account) {
                jdbctemplate.update("update account set money = ? where id = ? ",account.getmoney(),account.getid());
            }
        }
    2.4.2配置步骤
        2.4.2.1第一步:配置数据源和jdbctemplate
        <!-- 配置数据源 -->
        <bean id="datasource" 
                    class="org.springframework.jdbc.datasource.drivermanagerdatasource">
            <property name="driverclassname" value="com.mysql.jdbc.driver"></property>
            <property name="url" value="jdbc:mysql:///spring_day04"></property>
            <property name="username" value="root"></property>
            <property name="password" value="1234"></property>
        </bean>


    2.4.2.2第二步:配置事务管理器并注入数据源
        <!-- 配置jdbctemplate -->
        <bean id="jdbctemplate" class="org.springframework.jdbc.core.jdbctemplate">
            <property name="datasource" ref="datasource"></property>
        </bean>
    2.4.2.3第三步:在业务层使用@transactional注解
        @service("accountservice")
        @transactional(readonly=true,propagation=propagation.supports)
        public class accountserviceimpl implements iaccountservice {
            
            @autowired
            private iaccountdao accountdao;

            @override
            public account findaccountbyid(integer id) {
                return accountdao.findaccountbyid(id);
            }

            @override
            @transactional(readonly=false,propagation=propagation.required)
            public void transfer(string sourcename, string targename, float money) {
                //1.根据名称查询两个账户
                account source = accountdao.findaccountbyname(sourcename);
                account target = accountdao.findaccountbyname(targename);
                //2.修改两个账户的金额
                source.setmoney(source.getmoney()-money);//转出账户减钱
                target.setmoney(target.getmoney()+money);//转入账户加钱
                //3.更新两个账户
                accountdao.updateaccount(source);
                //int i=1/0;
                accountdao.updateaccount(target);
            }
        }

        该注解的属性和xml中的属性含义一致。该注解可以出现在接口上,类上和方法上。
        出现接口上,表示该接口的所有实现类都有事务支持。
        出现在类上,表示类中所有方法有事务支持
        出现在方法上,表示方法有事务支持。
        以上三个位置的优先级:方法>类>接口
    2.4.2.4第四步:在配置文件中开启spring对注解事务的支持
        <!-- 开启spring对注解事务的支持 -->
        <tx:annotation-driven transaction-manager="transactionmanager"/> 
        2.5基于纯注解的声明式事务控制(配置方式)重点
        2.5.1环境搭建
        2.5.1.1第一步:拷贝必备的jar包到工程的lib目录

        2.5.1.2第二步:创建一个类用于加载spring的配置并指定要扫描的包
        /**
         * 用于初始化spring容器的配置类
         */
        @configuration
        @componentscan(basepackages="com.baidu")
        public class springconfiguration {

        }
    2.5.1.3第三步:创建数据库表和实体类
        和基于xml的配置相同。略
    2.5.1.4第四步:创建业务层接口和实现类并使用注解让spring管理
        业务层接口和基于xml配置的时候相同。略

        /**
         * 账户的业务层实现类
         */
        @service("accountservice")
        public class accountserviceimpl implements iaccountservice {
            @autowired
            private iaccountdao accountdao;

            @override
            public account findaccountbyid(integer id) {
                return accountdao.findaccountbyid(id);
            }

            @override
            public void transfer(string sourcename, string targename, float money) {
                //1.根据名称查询两个账户
                account source = accountdao.findaccountbyname(sourcename);
                account target = accountdao.findaccountbyname(targename);
                //2.修改两个账户的金额
                source.setmoney(source.getmoney()-money);//转出账户减钱
                target.setmoney(target.getmoney()+money);//转入账户加钱
                //3.更新两个账户
                accountdao.updateaccount(source);
                int i=1/0;
                accountdao.updateaccount(target);
            }
        }

    2.5.1.5第五步:创建dao接口和实现类并使用注解让spring管理
        dao层接口和accountrowmapper与基于xml配置的时候相同。略

        @repository("accountdao")
        public class accountdaoimpl implements iaccountdao {

            @autowired
            private jdbctemplate jdbctemplate;
            
            @override
            public account findaccountbyid(integer id) {
                list<account> list = jdbctemplate.query("select * from account where id = ? ",new accountrowmapper(),id);
                return list.isempty()?null:list.get(0);
            }

            @override
            public account findaccountbyname(string name) {
                list<account> list =  jdbctemplate.query("select * from account where name = ? ",new accountrowmapper(),name);
                if(list.isempty()){
                    return null;
                }
                if(list.size()>1){
                    throw new runtimeexception("结果集不唯一,不是只有一个账户对象");
                }
                return list.get(0);
            }

            @override
            public void updateaccount(account account) {
                jdbctemplate.update("update account set money = ? where id = ? ",account.getmoney(),account.getid());
            }
        }

    2.5.2配置步骤
        2.5.2.1第一步:使用@bean注解配置数据源
        @bean(name = "datasource")
            public datasource createds() throws exception {
                drivermanagerdatasource datasource = new drivermanagerdatasource();
                datasource.setusername("root");
                datasource.setpassword("123");
                datasource.setdriverclassname("com.mysql.jdbc.driver");
                datasource.seturl("jdbc:mysql:///spring3_day04");
                return datasource;
            }
    2.5.2.2第二步:使用@bean注解配置配置事务管理器
        @bean
        public platformtransactionmanager 
                createtransactionmanager(@qualifier("datasource") datasource datasource) {
            return new datasourcetransactionmanager(datasource);
        }
        2.5.2.3第三步:使用@bean注解配置jdbctemplate
        @bean
        public jdbctemplate createtemplate(@qualifier("datasource") datasource datasource) 
        {
            return new jdbctemplate(datasource);
        }
    2.5.2.4第四步:在需要控制事务的业务层实现类上使用@transactional注解
        @service("accountservice")
        @transactional(readonly=true,propagation=propagation.supports)
        public class accountserviceimpl implements iaccountservice {
            
            @autowired
            private iaccountdao accountdao;

            @override
            public account findaccountbyid(integer id) {
                return accountdao.findaccountbyid(id);
            }

            @override
            @transactional(readonly=false,propagation=propagation.required)
            public void transfer(string sourcename, string targename, float money) {
                //1.根据名称查询两个账户
                account source = accountdao.findaccountbyname(sourcename);
                account target = accountdao.findaccountbyname(targename);
                //2.修改两个账户的金额
                source.setmoney(source.getmoney()-money);//转出账户减钱
                target.setmoney(target.getmoney()+money);//转入账户加钱
                //3.更新两个账户
                accountdao.updateaccount(source);
                //int i=1/0;
                accountdao.updateaccount(target);
            }
        }

        该注解的属性和xml中的属性含义一致。该注解可以出现在接口上,类上和方法上。
        出现接口上,表示该接口的所有实现类都有事务支持。
        出现在类上,表示类中所有方法有事务支持
        出现在方法上,表示方法有事务支持。
        以上三个位置的优先级:方法>类>接口。
    2.5.2.5第五步:使用@enabletransactionmanagement开启spring对注解事务的的支持
        @configuration
        @enabletransactionmanagement
        public class springtxconfiguration {
            //里面配置数据源,配置jdbctemplate,配置事务管理器。在之前的步骤已经写过了。
        }

在spring中开启事务的案例
    applicationcontext3.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"
            xmlns:tx="http://www.springframework.org/schema/tx"
            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
            http://www.springframework.org/schema/tx 
            http://www.springframework.org/schema/tx/spring-tx.xsd">
            
            <!-- 使用spring整合c3p0的连接池,没有采用属性文件的方式 -->
            <bean id="datasource" class="com.mchange.v2.c3p0.combopooleddatasource ">
                <property name="driverclass" value="com.mysql.jdbc.driver"/>
                <property name="jdbcurl" value="jdbc:mysql:///spring_04"/>
                <property name="user" value="root"/>
                <property name="password" value="root"/>
            </bean>
            
            <!-- 配置平台事务管理器 -->
            <bean id="transactionmanager" class="org.springframework.jdbc.datasource.datasourcetransactionmanager">
                <property name="datasource" ref="datasource"></property>
            </bean>
            <!-- 配置通知: 是spring框架提供通知,不是咋们自己编写的 -->
            <tx:advice id="myadvice" transaction-manager="transactionmanager">
                <tx:attributes>
                    <!-- 给具体的业务层的方法进行隔离级别,传播行为的具体的配置 -->
                    <tx:method name="pay" isolation="default" propagation="required"/>
                    <tx:method name="save*" isolation="default"></tx:method>
                    <tx:method name="find*" read-only="true"></tx:method>
                </tx:attributes>
            </tx:advice>
            <!-- 配置aop的增强 -->
            <aop:config>
                <!-- spring框架制作的通知,必须要使用该标签,如果是自定义的切面,使用aop:aspect标签 -->
                <aop:advisor advice-ref="myadvice" pointcut="execution(public * com.baidu.*.*serviceimpl.*(..))"></aop:advisor>
            </aop:config>
            
            <!-- 可以注入连接池 -->
            <bean id="accountdao" class="com.baidu.demo3.accountdaoimpl">
                <property name="datasource" ref="datasource"></property>
            </bean>
            <!-- 管理service -->
            <bean id="accountservice" class="com.baidu.demo3.accountserviceimpl">
                <property name="accountdao" ref="accountdao"></property>
            </bean>
            
        </beans>
在dao层对代码进行了优化,优化了jdbctemplate
    public class accountdaoimpl extends jdbcdaosupport implements accountdao {
        /*
    private jdbctemplate jdbctemplate;
    
    public void setjdbctemplate(jdbctemplate jdbctemplate) {
        this.jdbctemplate = jdbctemplate;
    }*/
    //减钱
    @override
    public void outmoney(string out, double money) {
        //jdbctemplate.update("update username set money = money - ? where name = ?",money,out);
        this.getjdbctemplate().update("update username set money = money - ? where name=?",money,out);
    }
    //加钱
    @override
    public void inmoney(string in, double money) {
        //jdbctemplate.update("update username set money = money + ? where name = ?",money,in);
        this.getjdbctemplate().update("update username set money = money + ? where name=?",money,in);
    }

}

xml和注解一起进行spring的事务管理
        applicationcontext4.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"
                xmlns:tx="http://www.springframework.org/schema/tx"
                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
                http://www.springframework.org/schema/tx 
                http://www.springframework.org/schema/tx/spring-tx.xsd">
                
                <!-- 开启注解的扫描 -->
                <context:component-scan base-package="com.baidu"/>
                <!-- 使用spring整合c3p0的连接池,没有采用属性文件的方式 -->
                <bean id="datasource" class="com.mchange.v2.c3p0.combopooleddatasource">
                    <property name="driverclass" value="com.mysql.jdbc.driver"/>
                    <property name="jdbcurl" value="jdbc:mysql:///spring_04"/>
                    <property name="user" value="root"/>
                    <property name="password" value="root"/>
                </bean>
                
                <!-- 配置jdbctemplate模板 -->
                <bean id="jdbctemplate" class="org.springframework.jdbc.core.jdbctemplate">
                    <property name="datasource" ref="datasource"></property>
                </bean>
                <!-- 配置平台事务管理器 -->
                <bean id="transactionmanager" class="org.springframework.jdbc.datasource.datasourcetransactionmanager">
                    <property name="datasource" ref="datasource"></property>
                </bean>
                <!-- 开启事务注解 -->
                <tx:annotation-driven transaction-manager="transactionmanager"></tx:annotation-driven>
                
            </beans>
service层用注解 :
    //实现类
        @service("accountservice")
        @transactional(isolation=isolation.default)
        public class accountserviceimpl implements accountservice {
            @resource(name="accountdao")
            private accountdao accountdao;
        //    public void setaccountdao(accountdao accountdao) {
        //        this.accountdao = accountdao;
        //    }
            //支付的方法
            @override
            public void pay(string out, string in, double money) {
                //模拟两个操作
                //减钱
                accountdao.outmoney(out, money);
                //模拟异常
                //int i = 10/0;
                accountdao.inmoney(in, money);
            }
        }
使用纯注解的方式进行spring事务管理 :
        /*
         * 配置类,spring声明式事务管理,纯注解的方式
         * 
         */
        @configuration
        @componentscan(basepackages="com.baidu.demo5")
        @enabletransactionmanagement    //纯注解的方式,开启事务注解
        public class springconfig {
            @bean(name="datasource")
            public datasource createdatasource() throws exception{
                combopooleddatasource datasource = new combopooleddatasource();
                datasource.setdriverclass("com.mysql.jdbc.driver");
                datasource.setjdbcurl("jdbc:mysql:///spring_04");
                datasource.setuser("root");
                datasource.setpassword("root");
                
                return datasource;
            }
            
            //把datasource注入进来
            @bean(name="jdbctemplate")
            @resource(name="datasource")
            public jdbctemplate createjdbctemplate(datasource datasource) {
                return new jdbctemplate(datasource);
            }
            
            //创建平台事务管理器对象
            @bean(name="transactionmanager")
            @resource(name="datasource")
            public platformtransactionmanager createtransactionmanager(datasource datasource) {
                return new datasourcetransactionmanager(datasource);
            }
            
        }
1 : 传播行为 : 解决业务层方法之间互相调用的问题.
    传播行为的默认值 : 保证save和update方法在同一个事务中.

2 : spring事务管理 : (1) : xml配置文件 ; (2) : xml+注解配置文件 ; (3) : 纯注解
    spring框架提供了接口和实现类,进行事务管理的.
        platformtransactionmanager接口 : 平台事务管理器,提供和回滚事务的.
            hibernatetransactionmanager : hibernate框架事务管理的实现类.
            datasourcetransactionmanager : 使用jdbc或者mybattis框架
        transactiondefinition接口 : 事务的定义的信息.提供很多常量,分别表示隔离级别,传播行为.
            传播行为 : 事务的传播行为,解决service方法之间的调用的问题.
        
    spring声明式事务管理,使用aop技术进行事务管理.
        通知/增强 : 事务管理的方法,不用咋们自己编写.需要配置.
        
        连接池 datasource ,存在connection ,使用jdbc进行事务管理 ,conn.commit()
                        |
                        |注入
        平台事务管理器(必须配置的),是spring提供接口,提交和回滚事务
                        |
                        |注入
        自己编写通知方法(事务管理),spring提供通知,配置通知
                        |
                        |注入
                配置aop增强 aop:config