XML based declarative transaction control configuration steps in Spring

Posted by fiorelina21 on Thu, 20 Feb 2020 07:36:28 +0100

1. Import Maven coordinates

<dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.2.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.6.8.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.2.2.RELEASE</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

2. Configuration of key Bean.xml

<bean id="accountService" class="com.joyTop.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"></property>
    </bean>

    <bean id="accountDao" class="com.joyTop.dao.impl.AccountDaoImpl">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <bean id="jdbcTemloate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <! -- configure data source -- >
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="Url" value="jdbc:mysql://localhost:3306/spring4_day3?characterEncoding=utf-8"></property>
        <property name="username" value="root"></property>
        <property name="password" value="123.com"></property>
    </bean>

    Configuration steps of XML based transaction control in spring
       1. Configure transaction manager
       2. Configure transaction notification
            At this point, we need to import constraints of transaction tx namespace and constraints, as well as aop
            Configure transaction notification with tx:advice tag
                Properties:
                   ID: enable unique ID for transaction notification
                   Transaction manager: provides a transaction manager reference for transaction notifications
        3. Configure common pointcut expressions in AOP
        4. Establish correspondence between transaction notification and pointcut expression
        5. Configure transaction properties
                 Is inside the notification tx:advice tag of the transaction
    -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    
    <! -- configure transaction notification -- >
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
         <! -- configure the properties of the transaction
                Isolation: used to specify the isolation level of the transaction. The DEFAULT value is DEFAULT, which means the DEFAULT isolation level of the database is used
                Timeout: transaction timeout. The default value is - 1, which means never timeout. If a value is specified, it is in seconds
                Propagation: used to specify the propagation behavior of a transaction. The default value is REQUIRED, which means there must be transactions. You can choose to add, delete, or modify them. You can choose SUPPORTS as the query method
                Read only: Specifies whether the transaction is read-only or not. Only the query method can be set to true. The default value is false, indicating read-write
                Rollback for: used to specify an exception. When the exception is generated, the transaction is rolled back. When other exceptions are generated, the transaction is not rolled back and has no default value. Indicates that any exception is rolled back.
                No rollback for: same as above
         -->
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED" read-only="false"/>
            <tx:method name="find" propagation="SUPPORTS" read-only="true"></tx:method>
        </tx:attributes>
    </tx:advice>

    <! -- configure AOP -- >
    <aop:config>
        <! -- configure pointcut expressions -- >
        <aop:pointcut id="pt1" expression="execution(* com.joyTop.service.impl.*.*(..))"/>
        <! -- establish correspondence between pointcut expression and transaction notification -- >
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor>
    </aop:config>

3.Dao uses inheritance of JdbcDaoSupport. accountDao in Bean.xml does not need to introduce JdbcTemplate, but directly introduces dataSource data source. In dao, super.getJdbcTemplate() is used to obtain JdbcTemplate

public class AccountDaoImpl extends JdbcDaoSupport implements IAccountDao {
    public Account findAccountById(float id) {
        List<Account> list = super.getJdbcTemplate().query("select * from account where id = ?", new BeanPropertyRowMapper<Account>(Account.class), id);
        return list.isEmpty() ? null : list.get(0);
    }
    public Account findAccountByName(String accountName) {
        List<Account> list = super.getJdbcTemplate().query("select * from account where name = ?", new BeanPropertyRowMapper<Account>(Account.class), accountName);
        if (list.isEmpty()) {
            return null;
        }
        if (list.size() > 1){
            throw new RuntimeException("The results are not unique");
        }
        return list.get(0);
    }
    public void updateAccount(Account account) {
         super.getJdbcTemplate().update("update account set money=? where id=?",account.getMoney(),account.getId());
    }
}

4.Service business layer

public class IAccountServiceImpl implements IAccountService {
    private IAccountDao accountDao;
    public void setAccountDao(IAccountDao accountDao) {
        this.accountDao = accountDao;
    }
    public Account findAccountById(Integer accountId) {
        return accountDao.findAccountById(accountId);
    }
    public void updateAccount(Account account) {
        accountDao.updateAccount(account);
    }
    public void transfer(String sourceName, String targetName, Float money) {
        System.out.println("transfer....");
        //2.1 query transfer out account by name
        Account source = accountDao.findAccountByName(sourceName);
        //2.2 query transfer in account by name
        Account target = accountDao.findAccountByName(targetName);
        //2.3 deduction from transfer out account
        source.setMoney(source.getMoney() - money);
        //2.4 transfer in account plus money
        target.setMoney(target.getMoney() + money);
        //2.5 update transfer out account
        accountDao.updateAccount(source);
//            int i=1/0;
        //2.6 update transfer in account
        accountDao.updateAccount(target);
    }
}

5. Test spring integer and Junit, annotate to test

/**
 * Using Junit unit testing: testing our configuration
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountServiceTest {
    @Autowired
    private IAccountService as;
    @Test
    public  void testTransfer(){
        as.transfer("aaa","bbb",100f);
    }
}

6. Maybe there is a problem with the imported Maven version, but it doesn't work out. If a small partner sees the problem, you can contact me. Thank you.

QQ:583083874
Published 4 original articles, praised 0, visited 17
Private letter follow

Topics: Spring JDBC MySQL Junit