Spring的事物控制

1. 程序中事務控制

1.1 環境準備

用戶訪問—》Action  --》 Service---》Dao

 

一個業務的成功:調用的service是執行成功的,意味着service中調用的所有的dao是執行成功的。 事務應該在Service層統一控制。

 

1)沒有應用事務的代碼:

2)模擬:

在service中調用2次dao, 希望其中一個dao執行失敗,整個操作要回滾。

 

1.2 事務控制概述

編程式事務控制

         自己手動控制事務,就叫做編程式事務控制。

         Jdbc代碼:

                   Conn.setAutoCommite(false);  //設置手動控制事務

         Hibernate代碼:

                   Session.beginTransaction();    //開啓一個事務

         【細粒度的事務控制:可以對指定的方法、指定的方法的某幾行添加事務控制】

         (比較靈活,但開發起來比較繁瑣:每次都要開啓、提交、回滾.)

 

聲明式事務控制

         Spring提供了對事務的管理,這個就叫聲明式事務管理。

         Spring提供了對事務控制的實現。用戶如果想用Spring的聲明式事務管理,只需要在配置文件中配置即可;不想使用時直接移除配置。這個實現了對事務控制的最大程度的解耦。

         Spring聲明式事務管理,核心實現就是基於Aop

         【粗粒度的事務控制:只能給整個方法應用事務,不可以對方法的某幾行應用事務。】

         (因爲aop攔截的是方法。)

 

         Spring聲明式事務管理器類:

                   Jdbc技術:DataSourceTransactionManager

                   Hibernate技術:HibernateTransactionManager

 

2. 聲明式事務管理

步驟:

         1) 引入spring-aop相關的4個jar文件

         2) 引入aop名稱空間  【XML配置方式需要引入】

         3) 引入tx名稱空間    【事務方式必須引入】

XML方式實現

1. DeptDao.java

public class DeptDao {

   

    // 容器注入JdbcTemplate對象

    private JdbcTemplatejdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {

        this.jdbcTemplate =jdbcTemplate;

    }

 

    public void save(Dept dept){

        String sql = "insert into t_dept (deptName) values(?)";

        jdbcTemplate.update(sql,dept.getDeptName());

    }

}

 

2. DeptService

public class DeptService {

   

    // 容器注入dao對象

    private DeptDaodeptDao;

    public void setDeptDao(DeptDao deptDao) {

        this.deptDao = deptDao;

    }

 

    /*

     * 事務控制?

     */

    public void save(Dept dept){

        // 第一次調用

        deptDao.save(dept);

       

        int i = 1/0; // 異常:整個Service.save()執行成功的要回滾

       

        // 第二次調用

        deptDao.save(dept);

    }

}

3. App 測試類

@Test

    public void testApp() throws Exception {

        //容器對象

        ApplicationContext ac = new ClassPathXmlApplicationContext("cn/itcast/a_tx/bean.xml");

       

        // 模擬數據

        Dept dept = new Dept();

        dept.setDeptName("測試:開發部");

       

        DeptService deptService = (DeptService) ac.getBean("deptService");

        deptService.save(dept);

       

    }

4. bean.xml  (Spring聲明式事務管理配置)

<?xmlversion="1.0"encoding="UTF-8"?>

<beansxmlns="http://www.springframework.org/schema/beans"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xmlns:p="http://www.springframework.org/schema/p"

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

 

   

    <!-- 1. 數據源對象: C3P0連接池 -->

    <beanid="dataSource"class="com.mchange.v2.c3p0.ComboPooledDataSource">

        <propertyname="driverClass"value="com.mysql.jdbc.Driver"></property>

        <propertyname="jdbcUrl"value="jdbc:mysql:///hib_demo"></property>

        <propertyname="user"value="root"></property>

        <propertyname="password"value="root"></property>

        <propertyname="initialPoolSize"value="3"></property>

        <propertyname="maxPoolSize"value="10"></property>

        <propertyname="maxStatements"value="100"></property>

        <propertyname="acquireIncrement"value="2"></property>

    </bean>

   

    <!-- 2. JdbcTemplate工具類實例 -->

    <beanid="jdbcTemplate"class="org.springframework.jdbc.core.JdbcTemplate">

        <propertyname="dataSource"ref="dataSource"></property>

    </bean>

   

    <!-- 3. dao實例 -->

    <beanid="deptDao"class="cn.itcast.a_tx.DeptDao">

        <propertyname="jdbcTemplate"ref="jdbcTemplate"></property>

    </bean>

 

    <!-- 4. service實例 -->

    <beanid="deptService"class="cn.itcast.a_tx.DeptService">

        <propertyname="deptDao"ref="deptDao"></property>

    </bean>

   

    <!-- #############5. Spring聲明式事務管理配置############### -->

    <!-- 5.1 配置事務管理器類 -->

    <beanid="txManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

        <propertyname="dataSource"ref="dataSource"></property>

    </bean>

   

    <!-- 5.2 配置事務增強(如果管理事務?) -->

    <tx:adviceid="txAdvice"transaction-manager="txManager">

        <tx:attributes>

            <tx:methodname="get*"read-only="true"/>

            <tx:methodname="find*"read-only="true"/>

            <tx:methodname="*"read-only="false"/>

        </tx:attributes>

    </tx:advice>

   

    <!-- 5.3 Aop配置:攔截哪些方法(切入點表表達式) + 應用上面的事務增強配置 -->

    <aop:config>

        <aop:pointcutexpression="execution(* cn.itcast.a_tx.DeptService.*())"id="pt"/>

        <aop:advisoradvice-ref="txAdvice"pointcut-ref="pt"/>

    </aop:config>

   

</beans>    

 

 


 

註解方式實現

使用註解實現Spring的聲明式事務管理,更加簡單!

步驟:

         1) 必須引入Aop相關的jar文件

         2) bean.xml中指定註解方式實現聲明式事務管理以及應用的事務管理器類

         3)在需要添加事務控制的地方,寫上: @Transactional

 

@Transactional註解:

         1)應用事務的註解

         2)定義到方法上: 當前方法應用spring的聲明式事務

         3)定義到類上:   當前類的所有的方法都應用Spring聲明式事務管理;

         4)定義到父類上: 當執行父類的方法時候應用事務。

 

Bean.xm

<?xmlversion="1.0"encoding="UTF-8"?>

<beansxmlns="http://www.springframework.org/schema/beans"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xmlns:p="http://www.springframework.org/schema/p"

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

 

   

    <!-- 1. 數據源對象: C3P0連接池 -->

    <beanid="dataSource"class="com.mchange.v2.c3p0.ComboPooledDataSource">

        <propertyname="driverClass"value="com.mysql.jdbc.Driver"></property>

        <propertyname="jdbcUrl"value="jdbc:mysql:///hib_demo"></property>

        <propertyname="user"value="root"></property>

        <propertyname="password"value="root"></property>

        <propertyname="initialPoolSize"value="3"></property>

        <propertyname="maxPoolSize"value="10"></property>

        <propertyname="maxStatements"value="100"></property>

        <propertyname="acquireIncrement"value="2"></property>

    </bean>

   

    <!-- 2. JdbcTemplate工具類實例 -->

    <beanid="jdbcTemplate"class="org.springframework.jdbc.core.JdbcTemplate">

        <propertyname="dataSource"ref="dataSource"></property>

    </bean>

   

    <!-- 事務管理器類 -->

    <beanid="txManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

        <propertyname="dataSource"ref="dataSource"></property>

    </bean>

   

    <!-- 開啓註解掃描 -->

    <context:component-scanbase-package="cn.itcast.b_anno"></context:component-scan>

   

    <!-- 註解方式實現事務:指定註解方式實現事務 -->

    <tx:annotation-driven transaction-manager="txManager"/>

</beans>     

DeptService

@Service

public class DeptService {

   

    @Resource

    private DeptDaodeptDao;

 

    /*

     * 事務控制?

     */

    @Transactional

    public void save(Dept dept){

        deptDao.save(dept);

        int i = 1/0;

        deptDao.save(dept);

    }

}

 

 

 

事務屬性

@Transactional(

            readOnly = false// 讀寫事務

            timeout = -1,       // 事務的超時時間不限制

            noRollbackFor = ArithmeticException.class// 遇到數學異常不回滾

            isolation = Isolation.DEFAULT,             // 事務的隔離級別,數據庫的默認

            propagation = Propagation.REQUIRED        // 事務的傳播行爲

    )

    public void save(Dept dept){

        deptDao.save(dept);

        int i = 1/0;

        deptDao.save(dept);

    }

事務傳播行爲:

         Propagation.REQUIRED

                   指定當前的方法必須在事務的環境下執行;

                   如果當前運行的方法,已經存在事務, 就會加入當前的事務;

         Propagation.REQUIRED_NEW

                   指定當前的方法必須在事務的環境下執行;

                   如果當前運行的方法,已經存在事務:  事務會掛起; 會始終開啓一個新的事務,執行完後;  剛纔掛起的事務才繼續運行。

 

 

舉例:

Class Log{

                   Propagation.REQUIRED  

                   insertLog(); 

}

 

         Propagation.REQUIRED

         Void saveDept(){

                   insertLog();    // 加入當前事務

                   .. 異常, 會回滾

                   saveDept();

         }

 

 

         ClassLog{

                   Propagation.REQUIRED_NEW  

                   insertLog(); 

}

 

         Propagation.REQUIRED

         Void saveDept(){

                   insertLog();    // 始終開啓事務

                   ..異常, 日誌不會回滾

                   saveDept();

         }

 

 

 

測試步驟:

         1)日誌表Log_

         2)LogService.java

                            insertLog();

 

 

 

4. Spring與Hibernate整合

Spring與Hibernate整合關鍵點:

         1) Hibernate的SessionFactory對象交給Spring創建;

         2) hibernate事務交給spring的聲明式事務管理。

 

SSH整合:

         Spring與Struts;

         Spring與hibernate整合;

 

 

SH整合步驟:

         1)引入jar包

                   連接池/數據庫驅動包

                   Hibernate相關jar

                   Spring核心包(5個)

                   Springaop 包(4個)

                   spring-orm-3.2.5.RELEASE.jar                 【spring對hibernate的支持】

spring-tx-3.2.5.RELEASE.jar                      【事務相關】

         2)配置

                   hibernate.cfg.xml

                   bean.xml

         3)搭建環境、單獨測試

                  

 

步驟實現

        

1. DeptDao.java

// 數據訪問層

public class DeptDao {

 

    // SpringHibernate整合: IOC容器注入

    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory) {

        this.sessionFactory = sessionFactory;

    }

 

    // 保存一個記錄

    // SpringHibernate整合:事務管理交給Spring

    public void save(Dept dept) {

        sessionFactory.getCurrentSession().save(dept);

    }

}

2. DeptService

public class DeptService {

 

    private DeptDaodeptDao;

    public void setDeptDao(DeptDao deptDao) {

        this.deptDao = deptDao;

    }

   

    public void save(Dept dept){

        deptDao.save(dept);

    }

}

 

3. App.java  測試

public class App {

   

    // 容器

    private ApplicationContextac = new ClassPathXmlApplicationContext("bean.xml");

 

    @Test

    public void testApp() throws Exception {

        DeptService deptServie = (DeptService) ac.getBean("deptService");

        System.out.println(deptServie.getClass());

       

        deptServie.save(new Dept());

    }

}

4. bean.xml 配置  【Spring管理SessionFactory的3中方式】

<?xmlversion="1.0"encoding="UTF-8"?>

<beansxmlns="http://www.springframework.org/schema/beans"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xmlns:p="http://www.springframework.org/schema/p"

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

 

    <!-- dao 實例 -->

    <beanid="deptDao"class="cn.itcast.dao.DeptDao">

        <propertyname="sessionFactory"ref="sessionFactory"></property>

    </bean>

   

    <!-- service 實例 -->

    <beanid="deptService"class="cn.itcast.service.DeptService">

        <propertyname="deptDao"ref="deptDao"></property>

    </bean>

   

    <!-- 數據源配置 -->

    <beanid="dataSource"class="com.mchange.v2.c3p0.ComboPooledDataSource">

        <propertyname="driverClass"value="com.mysql.jdbc.Driver"></property>

        <propertyname="jdbcUrl"value="jdbc:mysql:///hib_demo"></property>

        <propertyname="user"value="root"></property>

        <propertyname="password"value="root"></property>

        <propertyname="initialPoolSize"value="3"></property>

        <propertyname="maxPoolSize"value="10"></property>

        <propertyname="maxStatements"value="100"></property>

        <propertyname="acquireIncrement"value="2"></property>

    </bean>

   

    <!-- ###########SpringHibernate整合  start########### -->

   

    <!-- 方式(1)直接加載hibernate.cfg.xml文件的方式整合

    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">

        <property name="configLocation" value="classpath:hibernate.cfg.xml"></property>

    </bean>    -->

   

    <!-- 方式(2)連接池交給spring管理 【一部分配置寫到hibernate中,一份分在spring中完成】

    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">

        <property name="configLocation" value="classpath:hibernate.cfg.xml"></property>

        <property name="dataSource" ref="dataSource"></property>

    </bean> -->

   

    <!-- 【推薦】方式(3)所有的配置全部都在Spring配置文件中完成 -->

    <beanid="sessionFactory"class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">

        <!-- 注入連接池對象 -->

        <propertyname="dataSource"ref="dataSource"></property>

       

        <!-- hibernate常用配置 -->

        <propertyname="hibernateProperties">

            <props>

                <propkey="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>

                <propkey="hibernate.show_sql">true</prop>

                <propkey="hibernate.hbm2ddl.auto">update</prop>

            </props>

        </property>

       

        <!-- hibernate映射配置

        <property name="mappingLocations">

            <list>

                <value>classpath:cn/itcast/entity/*.hbm.xml</value>

            </list>

        </property>

        -->

        <propertyname="mappingDirectoryLocations">

            <list>

                <value>classpath:cn/itcast/entity/</value>

            </list>

        </property>

    </bean>

   

   

   

    <!-- ###########SpringHibernate整合  end########### -->

   

    <!-- 事務配置 -->

    <!-- a. 配置事務管理器類 -->

    <beanid="txManager"class="org.springframework.orm.hibernate3.HibernateTransactionManager">

        <propertyname="sessionFactory"ref="sessionFactory"></property>

    </bean>

    <!-- b. 配置事務增強(攔截到方法後如果管理事務?) -->

    <tx:adviceid="txAdvice"transaction-manager="txManager">

        <tx:attributes>

            <tx:methodname="*"read-only="false"/>

        </tx:attributes>

    </tx:advice>

    <!-- c. Aop配置 -->

    <aop:config>

         <aop:pointcutexpression="execution(* cn.itcast.service.*.*(..))"id="pt"/>

         <aop:advisoradvice-ref="txAdvice"pointcut-ref="pt"/>

    </aop:config>

   

</beans>    

 

        

細節

 

 

 

5. SSH整合

即:

         Spring與Struts整合

         Spring與Hibernate整合

 

需求:

         JSP頁面顯示員工信息  (查詢)

 

 

整合步驟:

         1) 引入SSH Jar文件

                   Struts核心jar

                   Hibernate核心jar

                   Spring

                            Core  核心功能

                            Web  對web模塊支持

                            Aop   aop支持

                            Orm   對hibernate支持

                            Jdbc/tx  jdbc支持包、事務相關包

 

         2)配置

                   Web.xml

                                     初始化struts功能、spring容器

                   Struts.xml   配置請求路徑與映射action的關係

                   Spring.xml  IOC容器配置

                            bean-base.xml     【公用信息】

                            bean-service.xml

                            bean-dao.xml

                            bean-action.xml

 

         3)開發

                   Entity/Dao/service/action

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章