Home > Java > javaTutorial > What are the two types of transactions in Java Spring?

What are the two types of transactions in Java Spring?

PHPz
Release: 2023-05-16 16:07:12
forward
1433 people have browsed it

    1. Transaction control method in Spring

    Spring’s transaction control can be divided into programmatic transaction control and Declarative transaction control.

    Programmatic

    Developers directly couple transaction code and business code together, which is not used in actual development.

    Declarative

    Developers use configuration to achieve transaction control, decoupling business code and transaction code, and using AOP ideas.

    2. Programmatic transaction control related objects

    2.1PlatformTransactionManager

    PlatformTransactionManager interface is spring's transaction manager interface, which provides our commonly used methods for operating transactions.

    What are the two types of transactions in Java Spring?

    What are the two types of transactions in Java Spring?

    ##2.2TransactionDefinition

    The TransactionDefinition interface provides transaction definition information (transaction isolation level, transaction propagation behavior, etc.)

    What are the two types of transactions in Java Spring?

    (1) Transaction isolation level

    Setting the isolation level can solve problems caused by transaction concurrency, such as dirty reads, unavailable Repeated reading and virtual reading (phantom reading).

    Note: Use the database default level. If the database is mysql, the default is repeatable read, oracle is read committed.

    ISOLATION_DEFAULT Use database default level

    ISOLATION_READ_UNCOMMITTED Read uncommitted

    ISOLATION_READ_COMMITTED Read committed ( Can solve dirty read problem)

    ISOLATION_REPEATABLE_READ Repeatable read (can solve dirty read and non-repeatable read problem)

    ISOLATION_SERIALIZABLE Serialization

    Can be solved:

    What are the two types of transactions in Java Spring?

    (2) Transaction propagation behavior

    Transaction propagation behavior refers to What is involved is how transaction control should be performed when a business method is called by another business method.

    What are the two types of transactions in Java Spring?

    Key points:

    What are the two types of transactions in Java Spring?

    • ##read-only

      (Whether it is read-only): It is recommended to set it to read-only when querying

    • timeout

      (timeout time): The default value is -1, there is no timeout limit. If so, set it in seconds

    • 2.3 TransactionStatus

    The TransactionStatus interface provides the specific running status of the transaction.

    What are the two types of transactions in Java Spring?You can simply understand the relationship between the three: the transaction manager performs transaction management by reading the transaction definition parameters, and then generates a series of transaction states.

    Transaction control in Spring is mainly implemented through these three APIs

    PlatformTransactionManager

    is responsible for the management of transactions. It is an interface and its subclasses are responsible for specific work

    TransactionDefinition

    Defines some relevant parameters of the transaction

    TransactionStatus

    Represents a real-time status of the transaction runningUnderstand the relationship between the three:

    Transaction manager

    performs transaction management by reading transaction definition parameters, and then generates a series of transaction status. 3. XML-based declarative transaction control [Key points]

    Declarative processing of transactions in the Spring configuration file instead of code processing. The bottom layer is implemented using AOP ideas.

    Declarative transaction control clear matters:

    Core business code (target object) (Who is the entry point?)

    Transaction enhancement code (Spring Transaction manager has been provided)) (Who is notified?)

    Aspect configuration (How to configure the aspect?) (Aspect = pointcut notification)

    3.1 Quick Start

    Use Spring declarative transaction control transfer business.

    Steps:

    1.Introduce the tx namespace

    2.Transaction manager notification configuration

    3.Transaction manager AOP configuration

    4. Test transaction control transfer business code

    (1)Introduce tx namespace

    <?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:tx="http://www.springframework.org/schema/tx"
           xmlns:aop="http://www.springframework.org/schema/aop"
           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/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
    ">
    Copy after login
    (2)Transaction manager notification configuration
      <!--事务管理器对象-->
        <!--<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="dataSource"/>
        </bean>--> 
    // 通知增强
        <tx:advice id="txAdvice" transaction-manager="transactionManager">
           //定义事务的一些属性 * 表示当前任意名称的方法都走默认配置
         <!--
                name: 切点方法名称
                isolation:事务的隔离级别
                propagation:事务的传播行为
                read-only:是否只读
                timeout:超时时间
            -->
            <tx:attributes>
                <tx:method name="transfer" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" timeout="-1"/>
                //CRUD常用配置
                <tx:method name="save*" propagation="REQUIRED"/>
                <tx:method name="delete*" propagation="REQUIRED"/>
                <tx:method name="update*" propagation="REQUIRED"/>
                <tx:method name="find*" read-only="true"/>
                <tx:method name="*"/>
            </tx:attributes>
        </tx:advice>
    Copy after login
    (3) Transaction manager AOP configuration
    When using spring to manage transactions declaratively, use aop:advisor to configure aop!
    //aop配置:配置切面   
    <aop:config>  
            <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.lagou.servlet.impl.AccountServiceImpl.*(..))"/>
        </aop:config>-->
    Copy after login

    Detailed configuration of transaction parameters:

    ##

    • name:切点方法名称

    • isolation:事务的隔离级别

    • propogation:事务的传播行为

    • timeout:超时时间

    • read-only:是否只读

    4.基于注解的声明式事务控制(重点)

    步骤:

    • 修改service层,增加事务注解

    • 修改spring核心配置文件,开启事务注解支持

    4.1 修改service层,增加事务注解

    @Service
    public class AccountServiceImpl implements AccountService {
      @Autowired
      private AccountDao accountDao;
        @Transactional(propagation = Propagation.REQUIRED, isolation =
    Isolation.REPEATABLE_READ, timeout = -1, readOnly = false)
      @Override
      public void transfer(String outUser, String inUser, Double money) {
        accountDao.out(outUser, money);
        int i = 1 / 0;
        accountDao.in(inUser, money);
     }
    }
    Copy after login

    4.2修改spring核心配置文件,开启事务注解支持

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w2.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">
      <!--省略之前datsSource、jdbcTemplate、组件扫描配置-->
      <!--事务管理器-->
      <bean id="transactionManager"
    class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
      </bean>
      <!--事务的注解支持-->
      <tx:annotation-driven/>
    </beans
    Copy after login

    4.3纯注解方式

    核心配置类:

    @Configuration  // 声明该类为核心配置类
    @ComponentScan("com.lagou")  // 包扫描
    @Import(DataSourceConfig.class) //导入其他配置类
    @EnableTransactionManagement //事务的注解驱动
    public class SpringConfig {
        @Bean
        public JdbcTemplate getJdbcTemplate(@Autowired DataSource dataSource){
            JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
            return jdbcTemplate;
        }
        @Bean
        public PlatformTransactionManager getPlatformTransactionManager(@Autowired DataSource dataSource){
            DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager(dataSource);
            return dataSourceTransactionManager;
        }
    }
    Copy after login

    数据源配置类:

    @PropertySource("classpath:jdbc.properties") //引入properties文件
    public class DataSourceConfig {
        @Value("${jdbc.driverClassName}")
        private String driver;
        @Value("${jdbc.url}")
        private String url;
        @Value("${jdbc.username}")
        private String username;
        @Value("${jdbc.password}")
        private String password;
        @Bean //会把当前方法的返回值对象放进IOC容器中
        public DataSource getDataSource(){
            DruidDataSource druidDataSource = new DruidDataSource();
            druidDataSource.setDriverClassName(driver);
            druidDataSource.setUrl(url);
            druidDataSource.setUsername(username);
            druidDataSource.setPassword(password);
            return druidDataSource;
        }
    }
    Copy after login

    The above is the detailed content of What are the two types of transactions in Java Spring?. For more information, please follow other related articles on the PHP Chinese website!

    Related labels:
    source:yisu.com
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template