1. 程式人生 > >15、Spring事務管理、SSH整合

15、Spring事務管理、SSH整合

Spring 第二天:
1. 代理模式
2. Aop程式設計
3.Spring對Jdbc的支援
JdbcTemplate工具類

思考:
程式的“事務控制”, 可以用aop實現! 即只需要寫一次,執行時候動態織入到業務方法上。
Spring提供了對事務的管理,開發者只需要按照Spring的方式去做就行。

目標:
1. Spring宣告式事務管理
* XML配置
*註解方式
2. Spring與Hibernate整合
3. SSH整合

  1. 程式中事務控制
    1.1 環境準備
    使用者訪問—》Action –》 Service—》Dao

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

1)沒有應用事務的程式碼:
2)模擬:
在service中呼叫2次dao, 希望其中一個dao執行失敗,整個操作要回滾。

開發步驟:
1. 後臺環境準備
資料庫、表/entity/dao/service
2. dao 的實現用JdbcTemplate
3. 物件建立都有Spring容器完成

1.2 事務控制概述
程式設計式事務控制
自己手動控制事務,就叫做程式設計式事務控制。
Jdbc程式碼:
Conn.setAutoCommite(false); // 設定手動控制事務
Hibernate程式碼:
Session.beginTransaction(); // 開啟一個事務
【細粒度的事務控制: 可以對指定的方法、指定的方法的某幾行新增事務控制】
(比較靈活,但開發起來比較繁瑣: 每次都要開啟、提交、回滾.)

宣告式事務控制
Spring提供了對事務的管理, 這個就叫宣告式事務管理。
Spring提供了對事務控制的實現。使用者如果想用Spring的宣告式事務管理,只需要在配置檔案中配置即可; 不想使用時直接移除配置。這個實現了對事務控制的最大程度的解耦。
Spring宣告式事務管理,核心實現就是基於Aop。
【粗粒度的事務控制: 只能給整個方法應用事務,不可以對方法的某幾行應用事務。】
(因為aop攔截的是方法。)

Spring宣告式事務管理器類:
    Jdbc技術:DataSourceTransactionManager
    Hibernate技術:HibernateTransactionManager
  1. 宣告式事務管理
    步驟:
    1) 引入spring-aop相關的4個jar檔案
    2) 引入aop名稱空間 【XML配置方式需要引入】
    3) 引入tx名稱空間 【事務方式必須引入】
    XML方式實現
  2. DeptDao.java
public class DeptDao {

    // 容器注入JdbcTemplate物件
    private JdbcTemplate jdbcTemplate;
    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());
    }
}
  1. DeptService
public class DeptService {

    // 容器注入dao物件
    private DeptDao deptDao;
    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);
    }
}
  1. 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);

    } 
  1. bean.xml (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: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連線池 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql:///hib_demo"></property>
        <property name="user" value="root"></property>
        <property name="password" value="root"></property>
        <property name="initialPoolSize" value="3"></property>
        <property name="maxPoolSize" value="10"></property>
        <property name="maxStatements" value="100"></property>
        <property name="acquireIncrement" value="2"></property>
    </bean>

    <!-- 2. JdbcTemplate工具類例項 -->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 3. dao例項 -->
    <bean id="deptDao" class="cn.itcast.a_tx.DeptDao">
        <property name="jdbcTemplate" ref="jdbcTemplate"></property>
    </bean>

    <!-- 4. service例項 -->
    <bean id="deptService" class="cn.itcast.a_tx.DeptService">
        <property name="deptDao" ref="deptDao"></property>
    </bean>

    <!-- #############5. Spring宣告式事務管理配置############### -->
    <!-- 5.1 配置事務管理器類 -->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 5.2 配置事務增強(如果管理事務?) -->
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <tx:attributes>
            <tx:method name="get*" read-only="true"/>
            <tx:method name="find*" read-only="true"/>
            <tx:method name="*" read-only="false"/>
        </tx:attributes>
    </tx:advice>

    <!-- 5.3 Aop配置: 攔截哪些方法(切入點表表達式) + 應用上面的事務增強配置 -->
    <aop:config>
        <aop:pointcut expression="execution(* cn.itcast.a_tx.DeptService.*())" id="pt"/>
        <aop:advisor advice-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

<?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: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連線池 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql:///hib_demo"></property>
        <property name="user" value="root"></property>
        <property name="password" value="root"></property>
        <property name="initialPoolSize" value="3"></property>
        <property name="maxPoolSize" value="10"></property>
        <property name="maxStatements" value="100"></property>
        <property name="acquireIncrement" value="2"></property>
    </bean>

    <!-- 2. JdbcTemplate工具類例項 -->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 事務管理器類 -->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 開啟註解掃描 -->
    <context:component-scan base-package="cn.itcast.b_anno"></context:component-scan>

    <!-- 註解方式實現事務: 指定註解方式實現事務 -->
    <tx:annotation-driven transaction-manager="txManager"/>
</beans>  

DeptService

@Service
public class DeptService {

    @Resource
    private DeptDao deptDao;

    /*
     * 事務控制?
     */
    @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();
    }


    Class Log{
        Propagation.REQUIRED_NEW  
        insertLog();  
}

    Propagation.REQUIRED
    Void  saveDept(){
        insertLog();    // 始終開啟事務
        .. 異常, 日誌不會回滾
        saveDept();
    }

測試步驟:
1)日誌表Log_
2)LogService.java
insertLog();

  1. Spring與Hibernate整合
    Spring與Hibernate整合關鍵點:
    1) Hibernate的SessionFactory物件交給Spring建立;
    2) hibernate事務交給spring的宣告式事務管理。

SSH整合:
Spring與Struts;
Spring與hibernate整合;

SH整合步驟:
1)引入jar包
連線池/資料庫驅動包
Hibernate相關jar
Spring 核心包(5個)
Spring aop 包(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 {

    // Spring與Hibernate整合: IOC容器注入
    private SessionFactory sessionFactory;
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    // 儲存一個記錄
    // Spring與Hibernate整合:事務管理交給Spring
    public void save(Dept dept) {
        sessionFactory.getCurrentSession().save(dept);
    }
}
2. DeptService
public class DeptService {

    private DeptDao deptDao;
    public void setDeptDao(DeptDao deptDao) {
        this.deptDao = deptDao;
    }

    public void save(Dept dept){
        deptDao.save(dept);
    }
}
  1. App.java 測試
public class App {

    // 容器
    private ApplicationContext ac = 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());
    }
}
  1. bean.xml 配置 【Spring管理SessionFactory的3中方式】
<?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: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 例項 -->
    <bean id="deptDao" class="cn.itcast.dao.DeptDao">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>

    <!-- service 例項 -->
    <bean id="deptService" class="cn.itcast.service.DeptService">
        <property name="deptDao" ref="deptDao"></property>
    </bean>

    <!-- 資料來源配置 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql:///hib_demo"></property>
        <property name="user" value="root"></property>
        <property name="password" value="root"></property>
        <property name="initialPoolSize" value="3"></property>
        <property name="maxPoolSize" value="10"></property>
        <property name="maxStatements" value="100"></property>
        <property name="acquireIncrement" value="2"></property>
    </bean>

    <!-- ###########Spring與Hibernate整合  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配置檔案中完成 -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <!-- 注入連線池物件 -->
        <property name="dataSource" ref="dataSource"></property>

        <!-- hibernate常用配置 -->
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>

        <!-- hibernate對映配置 
        <property name="mappingLocations">
            <list>
                <value>classpath:cn/itcast/entity/*.hbm.xml</value>
            </list>
        </property>
        -->
        <property name="mappingDirectoryLocations">
            <list>
                <value>classpath:cn/itcast/entity/</value>
            </list>
        </property>
    </bean>



    <!-- ###########Spring與Hibernate整合  end########### -->

    <!-- 事務配置 -->
    <!-- a. 配置事務管理器類 -->
    <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    <!-- b. 配置事務增強(攔截到方法後如果管理事務?) -->
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <tx:attributes>
            <tx:method name="*" read-only="false"/>
        </tx:attributes>
    </tx:advice>
    <!-- c. Aop配置 -->
    <aop:config>
         <aop:pointcut expression="execution(* cn.itcast.service.*.*(..))" id="pt"/>
         <aop:advisor advice-ref="txAdvice" pointcut-ref="pt"/>
    </aop:config>

</beans>     

細節

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