Spring declarative transaction management

1, Transaction:

        1. Four features: [ACID]

                ① atomicity: indivisibility, which means that multiple operations involved in a transaction are logically indispensable. All operations in the transaction are required to be executed or not executed

                ②   Consistency: the data is consistent, and all data are in the consistency state that meets the business rules. No matter how many operations a transaction involves, you must ensure that the data before and after the transaction is executed is correct; If one or more operations fail, you must undo all other operations and restore the data to the state before the transaction is executed, that is, rollback

                ③ isolation: it is required that multiple transactions will not interfere with each other during concurrent execution

                ④ durability: after the transaction is completed, the changes to the data are permanently saved and written to the persistent memory, which will not be affected by various system errors or other unexpected conditions

         2. Three behaviors:

                ① Start transaction: connection. Setautocommit (flash)

                ② Commit transaction: connection.commit()

                ③ Rollback transaction: connection.rollback()

        3. Programming transaction management:    

                 1) Get database Connection object

                 2) Cancel automatic commit of transaction

                 3) Perform operation

                 4) Manually commit the transaction when the operation completes normally

                 5) Rollback transaction on execution failure

                 6) Close related resources

      Conclusion: lack of programming transaction management, writing transaction management code [non business code] and business code together, resulting in code confusion and code dispersion.

      In this case, you need to use the AOP idea [horizontal extraction first, and then dynamic weaving] to manage transactions: declarative transaction management

        4. Declarative transaction management:

                1) Import related jar packages

                        spring-aspects-5.3.1.jar

                         com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar   < Dependent on jar package >

                2) Enable declarative transaction management support

                3) Add @ Transactional on the method or class that needs transaction management

         5. Do not use transaction management issues

            Case: take buying books as an example

 /**
     * Buy book - > query book price - > Modify inventory - > Modify balance
     * @param userId
     * @param isbn
     */
    public void purchase(String userId, String isbn) {
        //1. Query book price
        Integer price = bookShopDao.getBookPriceByIsbn(isbn);
        //2. Modify inventory
        bookShopDao.updateBookStock(isbn);
        //3. Modify balance
        bookShopDao.updateUserBalance(userId,price);
    }
@Test
    public void testBookShopService(){
        ApplicationContext context =
                new ClassPathXmlApplicationContext("applicationContext_transaction.xml");
        
       BookShopServiceImpl bookShopService = context.getBean("bookShopService", BookShopServiceImpl.class);

        bookShopService.purchase("101","1002");
    }

  There are three steps in the purchase() method, and transaction management should be used; If transaction management is not used, the problem of modifying inventory but not modifying balance may occur

      6. Using transaction management  

        1) Import jar package

<!--spring-aspects-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>5.3.1</version>
        </dependency>

        2) Enable claim transaction management support

<!--    Assembly transaction manager-->
    <bean id="transactionManger" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--    Open declarative transaction management-->
    <tx:annotation-driven transaction-manager="transactionManger"></tx:annotation-driven>

          3) Add @ Transactional on the method or class that needs transaction management  

/**
     * Buy book - > query book price - > Modify inventory - > Modify balance
     * @param userId
     * @param isbn
     */
    @Transactional
    public void purchase(String userId, String isbn) {
        //1. Query book price
        Integer price = bookShopDao.getBookPriceByIsbn(isbn);
        //2. Modify inventory
        bookShopDao.updateBookStock(isbn);
        //3. Modify balance
        bookShopDao.updateUserBalance(userId,price);
    }
 @Test
    public void testBookShopService(){
        ApplicationContext context =
                new ClassPathXmlApplicationContext("applicationContext_transaction.xml");

        //Transaction declarative transaction management [cannot be received with BookShopServiceImpl, because the code object and the target object are brothers]
        /*An error org.springframework.beans.factory.beannotofrequiredtypeexception will be reported: bean named 'bookshopservice' is expected to be of type 'com.atguigu.service
          BookShopServiceImpl' but was actually of type 'com.sun.proxy.$Proxy16'*/
       //BookShopServiceImpl bookShopService = context.getBean("bookShopService", BookShopServiceImpl.class);

        BookShopService bookShopService = context.getBean("bookShopService", BookShopService.class);

        bookShopService.purchase("101","1001");
    }

        7. Attributes in declarative transaction management

        1) Transaction propagation behavior: when a transaction method is called by another method, you must specify how the transaction should propagate. For example, a method may continue to run in an existing transaction, or it may open a new transaction and run in its own transaction.

        

        2) Transaction isolation level

        3) Transaction timeout       

        4)     Transaction read only

        5)   Transaction exception rollback [no rollback]

2, JdbcTemplate framework in Spring

1. Introduction to JdbcTemplate

  • JdbcTemplate is a persistence layer framework [similar to: Mybatis]

2. Steps to build a JdbcTemplate

  • Import related jar packages

        <!--spring-context-->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>5.3.1</version>
            </dependency>
            <!--spring-jdbc-->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>5.3.1</version>
            </dependency>
            <!--spring-orm-->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-orm</artifactId>
                <version>5.3.1</version>
            </dependency>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>1.18.12</version>
                <scope>compile</scope>
            </dependency>
  • Write core configuration file

  • Assemble the JdbcTemplate
    <!--    to configure JdbcTemplate-->
        <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    <!--        Configure data source properties-->
            <property name="dataSource" ref="dataSource"></property>
        </bean>
    
  • Use the corresponding method of JdbcTemplate

3. JdbcTemplate common API s

  • update(String sql,Object... params)         Addition, deletion and modification of general Party

  • batchUpdate(String sql,List<Object[]> params)       General method for batch addition, deletion and modification

    • queryForObject()
      • queryForObject(String sql,Class clazz,Object... params)

        • Query a single value: select count(1) from table

      • queryForObject(String sql,RowMapper<T> mapper,Object... params)

        • Query a single object: select col1, col2... From table where id =?

  • query(String sql,RowMapper<T> mapper,Object... params)

    • Query multiple objects, general method

        

Keywords: Spring

Added by speedamp on Fri, 15 Oct 2021 22:06:43 +0300