Spring事務配置管理、分かりやすく、詳細[声明式]

63404 ワード

Spring事務配置説明
Spring特別な説明がない場合は、一般的にデータストアに関するデータ操作事務操作を指します.データの永続的な動作のためのトランザクション構成は、一般的に3つのオブジェクト、データソース、トランザクションマネージャ、およびトランザクションエージェントメカニズムがある.
Springは、複数のベース層データソースの実装と複数のタイプのトランザクションマネージャを提供します.すべてのマネージャは、Platform Transation Managerインターフェースに基づいて、それぞれのトランザクションポリシーを実現します.
Spring事務管理はAOPカットエージェント技術を用いて実現され、AOPは注目点を分離し、事務の原子性を保証し、一定の技術を用いてこの注目点を完全な注目点に織り込み、単独のコンポーネントでは実現できない機能を実現し、対象プログラミングがいくつかの方法で実現しにくい操作を解決する.オブジェクト指向のスイッチング原則をよりよくサポートします.
下のデータソースの設定
優先的にデータソースの設定を読み込みます.propertiesファイル.
<bean id="loadProperties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:META-INF/mybatis/mysql.properties</value>
                <value>classpath:META-INF/spring/hibernate.properties</value>
            </list>
        </property>
</bean>
mysql.properties:
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/springdb
username=root
password=xxxxx
filters=stat
initialSize=2
maxActive=300
maxWait=60000
timeBetweenEvictionRunsMillis=60000
minEvictableIdleTimeMillis=300000
validationQuery=SELECT 1
testWhileIdle=true
testOnBorrow=false
testOnReturn=false
poolPreparedStatements=false
maxPoolPreparedStatementPerConnectionSize=200
ヒベルナ.properties:
# hibernate.X
hibernate.connection.driverClass=org.gjt.mm.mysql.Driver
hibernate.connection.url=jdbc:mysql://localhost:3306/springdb?useUnicode=true&amp;characterEncoding=utf-8
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.connection.username=root
hibernate.connection.password=xxxxx
hibernate.show_sql=true
hibernate.hbm2ddl.auto=create-drop
 
1.JDBC方式:
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${driver}"></property>
        <property name="url" value="${url}"></property>
        <property name="username" value="${username}"></property>
        <property name="password" value="${password}"></property>
</bean>
2. c 3 p 0方式:
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
        destroy-method="close">
        <!--            -->
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
        <!--         URL -->
        <property name="jdbcUrl" value="jdbc:mysql://localhost/springdb"/>
        <!--             -->
        <property name="user" value="root"/>
        <!--            -->
        <property name="password" value="xxxxx"/>
        <!--                  -->
        <property name="maxPoolSize" value="40"/>
        <!--                  -->
        <property name="minPoolSize" value="1"/>
        <!--                   -->
        <property name="initialPoolSize" value="1"/>
        <!--                      -->
        <property name="maxIdleTime" value="20"/>
</bean>
3. dbcp方式:
<beans>
  <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
   <property name="driverClassName" value="${driver}"></property>
   <property name="url" value="${url}"></property>
   <property name="username" value="${username}"></property>
   <property name="password" value="${password}"></property>
</bean>
4.Alibaba Druid方式:
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close" init-method="init" >
        <property name="url" value="${url}?useUnicode=true&amp;characterEncoding=utf-8"></property>
        <property name="driverClassName" value="${driver}"></property>
        <property name="username" value="${username}"></property>
        <property name="password" value="${password}"></property>
        <property name="filters" value="${filters}"></property>
        <property name="maxActive" value="${maxActive}"></property>
        <property name="maxWait" value="${maxWait}"></property>
        <property name="timeBetweenEvictionRunsMillis" value="${timeBetweenEvictionRunsMillis}"></property>
        <property name="minEvictableIdleTimeMillis" value="${minEvictableIdleTimeMillis}"></property>
        <property name="validationQuery" value="${validationQuery}"></property>
        <property name="testWhileIdle" value="${testWhileIdle}"></property>
        <property name="testOnBorrow" value="${testOnBorrow}"></property>
        <property name="testOnReturn" value="${testOnReturn}"></property>
        <property name="poolPreparedStatements" value="${poolPreparedStatements}"></property>
        <property name="maxPoolPreparedStatementPerConnectionSize" value="${maxPoolPreparedStatementPerConnectionSize}"></property>
</bean>
5.JNDIグローバル構成方式:
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">      
     <property name="jndiName" value="${jndiName}"></property> 
</bean>
6.カスタムDataSource:
<bean id="dataSource" class="me.study.hnmapper.utils.CustomDataSource">
   <property name="driverClass" value="oracle.jdbc.driver.OracleDriver"></property>
   <property name="driverUrl" value="jdbc:oracle:thin:@10.30.2.204:1527:sec"></property>
   <property name="username" value="apps"></property>
   <property name="password" value="secapp29"></property>
</bean>
Custoom Data Source:
package me.study.hnmapper.utils;

import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.logging.Logger;

import javax.sql.DataSource;

public class CustomDataSource implements DataSource {

    private String driverClass;
    private String driverUrl;
    private String username;
    private String password;

    @Override
    public PrintWriter getLogWriter() throws SQLException {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void setLogWriter(PrintWriter out) throws SQLException {
        // TODO Auto-generated method stub

    }

    @Override
    public void setLoginTimeout(int seconds) throws SQLException {
        // TODO Auto-generated method stub

    }

    @Override
    public int getLoginTimeout() throws SQLException {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public <T> T unwrap(Class<T> iface) throws SQLException {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public Connection getConnection() throws SQLException {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Connection getConnection(String username, String password)
            throws SQLException {
        // TODO Auto-generated method stub
        // TODO Auto-generated method stub
        Connection conn = null;
        try {
            Class.forName(driverClass);
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        conn = DriverManager.getConnection(driverUrl, username, password);

        return conn;
    }

    public String getDriverClass() {
        return driverClass;
    }

    public void setDriverClass(String driverClass) {
        this.driverClass = driverClass;
    }

    public String getDriverUrl() {
        return driverUrl;
    }

    public void setDriverUrl(String driverUrl) {
        this.driverUrl = driverUrl;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

}
6.Hibernate方式は、Session Factoryをデータソースとして利用しています.
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="mappingLocations" >
            <list>
                <value>classpath*:model/*.hbm.xml</value>
            </list>
        </property>
        <!-- packagesToScan        package     @Entity class -->
        <!-- 
        <property name="packagesToScan">
            <list>
                <value>hibernatelibs.model*</value>
            </list>
        </property>
         -->
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
                <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
            </props>
        </property>
</bean>
Transaction Manager事務マネージャの設定
1.JDBC Transactionager配置;
<bean id="transactionManager" 
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--   DataSourceTransactionManager      DataSource    -->
        <property name="dataSource" ref="dataSource"/>
</bean>
2.ヒッベルナタTransactionagerの設定:
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
</bean>
3.Jta Transation Managerの設定: 
<bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager"/>
JtaはアプリケーションサーバでJNDI検索に依存していますが、JTMやJObject Webに基づくものもあります. AtomikosというuserTransationが実現します.
Platform Transation ManagerはSpringビジネス戦略の核心となるインターフェースであり、Springは事務の実現をサポートしないで、包装の下の事務を担当しています.Platform Transationインターフェースに基づく各種の具体的な実現を分離します.どのようなビジネス戦略をサポートするのか、Springはどのようなビジネス戦略をサポートしますか?Spring声明式事務管理は、基本的なAOPカットエージェント技術の実現であり、XMLまたはAnnotationの構成に基づいた基本的な実現であり、Platform Transationは、各種の管理機構に対して統一操作インターフェースを提供しており、各種の管理メカニズムは、Platform Transationインターフェースに基づいて具体的な事務処理を実現しなければならない.Springトランザクション構成は、様々なタイプのトランザクション管理機構間で容易に切り替えることができる.
Platform Transationが提供するインターフェースは以下の通りである.
public interface PlatformTransactionManager {  
       TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException;  
       void commit(TransactionStatus status) throws TransactionException;  
       void rollback(TransactionStatus status) throws TransactionException;  
} 
 
一般的な事務機構としては、JdoTransation Manager、Jpa Transation Managerがあります.他にも、WebSphere UowTransation Manager、WebLogic JtaTransation Managerなどがあります.
事務代理機構
1.pointcut通知方式(最も一般的な方式)を使用する:
 最初にtx名前空間を設定します.
<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-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
通知項目の設定<tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="*" /> <!-- , query* query ,   propagation, isolation, ( )timeout_xx, read-only -->
        </tx:attributes>
</tx:advice>
<tx:methodの設定項目:
name:クラスにマッチする方法では、springはクラスの方法の形だけをサポートしています.パターンマッチングに対しては、perlの正規表現をサポートしてもいいし、aspectjもサポートしています.デフォルトはAspecJをサポートしています.
<tx:method name="*" ... /> <!--        -->
<tx:method name="get*" ... /> <!--       get        -->
<tx:method name="save*" ... /> <!--       save        -->
...
isolation: 
1、Serializable:      ,      ,      ;

2、REPEATABLE_READ:                         (  )   。   “   ” “      ”   ,            。

3、READ_COMMITTED:               ,                            ,   “   ”。           。

4、Read_Uncommitted:                 。                。

5、Default   。
プロモーション: Springは7つの伝播行為をサポートしています.EJBのCMTよりも多いです.
1. Required=>PROPAGATION_REQUIRED:           ,         ;
2. RequiresNew=>PROPAGATION_REQUIRES_NEW:              ,        ;
3. Supports=>PROPAGATION_SUPPORTS:         ,           ;
4. NotSupported=>PROPAGATION_NOT_SUPPORTED:      ,    ,  ,        ;
5. Mandatory=>PROPAGATION_MANDATORY:        ,     ,    ;
6. Never=>PROPAGATION_NEVER:      ,    ,    ;
7. Nested=>PROPAGATION_NESTED:     ,       ,         ;(             ,               )
timeout=「5」またはtimeout_xx:例えば:timeout_5;タイムアウト5秒を表します.
完全なtx:method:
<tx:method propagation="REQUIRED" isolation="REPEATABLE_READ" timeout="5" read-only="true" />
もう一つの構成は、具体的なbean内に配置されている:
<bean id="xxxxDao">
    <!-- ... -->
    <property name="transactionAttributes">  
            <props>  
                <prop key="*">PROPAGATION_REQUIRED,REPEATABLE_READ,timeout_5,readOnly</prop>
            </props>  
    </property>
</bean>
設定aop:config:
<aop:config>
        <!--                -->
        <aop:pointcut expression="execution(* springlibs.service.*.*(..))" id="puintCutid" /> <!--      component-scan -->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="puintCutid" />
</aop:config>
expression表現: execution(*springlibs.service.*.))
最初の*:すべての戻り値の種類を表します.
二つ目の*:すべてのクラスを表します.
第三の*:すべての方法を表します.
点式の例を入力:
1>. execution(*springlibs.service.*.*)はspriglibs.serviceの下にあるすべての種類とすべての方法を表します.
2>. execution(*springlibs.service.*.save*))はspriglibs.serviceのすべてのsaveで始まる方法を表します.
3>. execution(public*spriglibs.service.*))はspriglibs.serviceの下のすべての公共方法を表します.
pointcutはいくつかの接続点の集合を表し、expressionを用いてこの集合を表現する.advisorここではpointcutの接点とadviceの通知を接続する役割とします.
2.一つのbeanは一つの事務に対応する;
配置dao実現bean:
<bean id="xxxDaotarget" class="springlibs.dao.xxxDaoImpl">
    <!-- 
    property name="sessionFactory" ref="sessionFactory" />
    -->
</bean>
Daoに事務を配置:
<bean id="xxxDao"  
        class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">  
           <!--         -->  
           <property name="transactionManager" ref="transactionManager" />     
        <property name="target" ref="xxxDaotarget" />  
        <!--        -->  
        <property name="transactionAttributes">  
            <props>  
                <prop key="*">PROPAGATION_REQUIRED</prop>
            </props>  
        </property>  
</bean>  
3.すべてのbeanは基本クラスを共有します.
<bean id="transactionBase"  
            class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"  
            lazy-init="true" abstract="true">  
        <!--         -->  
        <property name="transactionManager" ref="transactionManager" />  
        <!--        -->  
        <property name="transactionAttributes">  
            <props>  
                <prop key="*">PROPAGATION_REQUIRED</prop>  
            </props>  
        </property>  
</bean>    
Daoに事務を配置:
<bean id="xxxDao" parent="transactionBase">
        <property name="target">
            <bean id="xxxDaoImpl" class="springlibs.dao.xxxDaoImpl"></bean>
        </property>
</bean>
4.スクリーンセーバーを使う:
<bean id="transactionInterceptor"  
        class="org.springframework.transaction.interceptor.TransactionInterceptor">  
        <property name="transactionManager" ref="transactionManager" />  
        <!--        -->  
        <property name="transactionAttributes">  
            <props>  
                <prop key="*">PROPAGATION_REQUIRED</prop>  
            </props>  
        </property>  
</bean>
      
<bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">  
        <property name="beanNames">  
            <list>  
                <value>*Dao</value>
            </list>  
        </property>  
        <property name="interceptorNames">  
            <list>  
                <value>transactionInterceptor</value>  
            </list>  
        </property>  
</bean>
 Daoに事務を配置する.
<!--   DAO   -->
<bean id="xxxDao" class="springlibs.dao.xxxDaoImpl">
        <!--
        <property name="sessionFactory" ref="sessionFactory" />
        -->
</bean>
5.Annotation方式を使う:
<tx:annotation-driven transaction-manager="transactionManager"  proxy-target-class="true"/>
proxy-targt classはtrueである:CGlibを使用して増加した代理を作成する;falseのために標準JDKを使って作成されます.
クラスレベルまたは方法で@Transation注入を使用することができる.
注@Transactionの類または方法は、自身に事務行為がなく、事務として認識されるものであり、実はtx:annotationn-drivenの配置が事務を開始したものである.