spring configuration transaction manager

  In Spring database transaction is carried out by PlatformTransactionManager management, jdbcTemplate can not support the transaction, and can support transactions is org.springframework.transaction.support.TransactionTemplate template, it is a Spring transaction manager provided a template
  • affairs create, commit and rollback is done by PlatformTransactionManager interface.
  • When an abnormal transaction rolls back the transaction, all exceptions are rolled back in the default implementation. We can modify the rollback when some abnormality occurs or does not roll back the transaction by configuration.
  • When no abnormality, commits the transaction.

  JTA transaction support, commonly used DataSourceTransactionManager, it inherits the abstract transaction manager AbstractPlatformTransactionManager, and AbstractPlatformTransactionManager has achieved PlatformTransactionManager. Spring so you can use that as a method PlatformTransactionManager interface source code to see, create, commit or roll back the transaction.

Configuring Transaction Manager

  MyBatis frame for most of the transaction manager is DataSourceTransactionManager (org.springframework.jdbc.datasource.DataSourceTransactionManager), therefore this embodiment will be explained below. If you are using a persistence framework Hibernate, then you have to use a spring-orm package org.springframework.orm.hibernate4.HibernateTransactionManager. They are very much the same, in general we use, will join the XML namespace of the transaction. The following configure a transaction manager

<?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: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-4.0.xsd
      http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
      http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
      http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <!-- 数据库连接池 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/springmvc?useSSL=false&amp;serverTimezone=Hongkong&amp;characterEncoding=utf-8&amp;autoReconnect=true"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
        <property name="maxActive" value="255"/>
        <property name="maxIdle" value="5"/>
        <property name="maxWait" value="10000"/>
    </bean>

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- 配置数据源事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

</beans>

 

  Here we introduced first XML namespace, and then define the database connection pool, so DataSourceTransactionManager used to define the database transaction manager, and injected database connection pool. Spring so I know you have to delegate database transactions to the transaction manager transactionManager managed. When jdbcTemplate source code analysis, the author has pointed out that the production and release database resources if not entrusted to a database administrator, then jdbcTemplate by the management, but this time has been entrusted to the transaction manager, so the database and transaction resources have been jdbcTemplate handled by the transaction manager.

  You can use declarative transaction or programmatic transaction in the Spring, and now almost no programmatic transaction, because it produces redundancy, code readability is poor. Declarative transaction can be divided into XML configuration and annotation affairs, but XML also has not used the way, the current mainstream method is annotated @Transactional.

Implement database transaction with the Spring Java configuration

  Manner to achieve Spring Java configuration database transaction, annota-tionDrivenTransactionManager need to implement the method in an interface configuration TransactionManagementConfigurer class. Spring will annotationDrivenTransactionManager method returns the transaction manager as transaction manager program
  Listing: Using Java database configuration to achieve Spring things

package com.ssm.chapter13.config;

import org.apache.commons.dbcp.BasicDataSourceFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
importorg.springframework.transaction.annotation.TransactionManagementConfigurer; 

Import javax.sql.DataSource;
 Import java.util.Properties; 

@Configuration 
@ComponentScan ( . "com.ssm.chapter13 *" )
 // use the event-driven manager 
@EnableTransactionManagement
 public  class 's JavaConfig the implements TransactionManagementConfigurer { 

    // data source 
    Private the dataSource the dataSource = null ; 

    / ** 
     * configuration data source *. @return data source.
      * / 
    @Bean (name = "the dataSource" )
     public DataSource initDataSource() {
        if (dataSource != null) {
            return dataSource;
        }
        Properties props = new Properties();
        props.setProperty("driverClassName", "com.mysql.cj.jdbc.Driver");
        props.setProperty("url", "jdbc:mysql://localhost:3306/springmvc?useSSL=false&serverTimezone=Hongkong&characterEncoding=utf-8&autoReconnect=true");
        props.setProperty("username", "root");
        props.setProperty("password", "123456");
        props.setProperty("maxActive", "200");
        props.setProperty("maxIdle", "20");
        props.setProperty("maxWait", "30000");
        try {
            dataSource = BasicDataSourceFactory.createDataSource(props);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dataSource;
    }

    /**
     * 配置jdbcTemplate   * @return jdbcTemplate
     */
    @Bean(name = "jdbcTemplate")
    public JdbcTemplate initjdbcTemplate() {
        JdbcTemplate jdbcTemplate = New new the JdbcTemplate (); 
        jdbcTemplate.setDataSource (initDataSource ()); 
        return the jdbcTemplate; 
    } 

    / ** 
     * implement interface methods, such returns database transaction manager 
     * / 
    @Override 
    @Bean (name = "the transactionManager" )
     public the PlatformTransactionManager annotationDrivenTransactionManager ( ) { 
        DataSourceTransactionManager the transactionManager = new new DataSourceTransactionManager ();
         // data source provided the transaction manager manages 
        transactionManager.setDataSource (initDataSource ());
         return the transactionManager; 
    } 
}

 

  TransactionManagementConfigurer interface implements the method defined annotation DrivenTransactionManager, and we use DataSourceTransactionManager definition database instance to the transaction manager, and the data source is provided to it. Be aware that using annotations @EnableTransactionManagement, use transaction @ Transactional annotations in the Spring context, Spring will know to use the database transaction manager manages the affairs.

Programmatic transaction

  Programmatic transaction management services by way of the code, in other words, the transaction will be accomplished by the developers own code, where the need to use a transaction definition class interface --TransactionDefinition, temporarily not in-depth introduction, we just use the default implementation class --DefaultTransactionDefinition it.
  Listing: programmatic transaction

package com.ssm.chapter13.main;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

public class MainTest {

    public static void main(String[] args) {

        ApplicationContext ctx = new ClassPathXmlApplicationContext("ssm/chapter13/spring-cfg.xml");//ctx为Spring IoC容器

        JdbcTemplate jdbcTemplate = ctx.getBean(JdbcTemplate.class);
        //事务定义类
        TransactionDefinition def = new DefaultTransactionDefinition();
        PlatformTransactionManager transactionManager = ctx.getBean(PlatformTransactionManager.class);
        TransactionStatus status = transactionManager.getTransaction(def);
        try {
            //执行SQL语句
            jdbcTemplate.update("insert into t_role(role_name, note) " + "values('role_name_transactionManager', 'note_transactionManager')");
            //提交事务
            transactionManager.commit(status);
        } catch (Exception ex) {
            //回滚事务
            transactionManager.rollback(status);
        }

    }


}

 

  You can see from the code all transactions are carried out by the developer's own control, because the transaction has handed over management of the transaction manager, so jdbcTemplate own database resource management has been by the transaction manager, so that when it is finished execute insert statement does not actually commit, this method need to use commit transaction manager, and roll back the transaction rollback method is required.
Of course, this is the easiest way to use, since that is not the mainstream way, even almost non-recommended method used, the reason is because it introduces the code flow clearer understanding of the program contribute to the future of transaction .

  Programmatic transaction type is a transaction agreement, in most cases, when using database transactions, most of the scenes is an abnormality has occurred in the code, the need to roll back the transaction, the transaction is committed when the abnormality is without the risk of so as to ensure the consistency of data in the database.

Guess you like

Origin www.cnblogs.com/ooo0/p/11029612.html