Spring5(18)- 基於 xml 的聲明式事務控制

1 DAO

  • 接口
public interface IAccountDao {

    /**
     * 根據Id查詢賬戶
     * @param accountId
     * @return
     */
    Account findAccountById(Integer accountId);

    /**
     * 根據名稱查詢賬戶
     * @param accountName
     * @return
     */
    Account findAccountByName(String accountName);

    /**
     * 更新賬戶
     * @param account
     */
    void updateAccount(Account account);
}

  • 實現類
/**
 * 賬戶的持久層實現類
 */
public class AccountDaoImpl extends JdbcDaoSupport implements IAccountDao {


    @Override
    public Account findAccountById(Integer accountId) {
        List<Account> accounts = super.getJdbcTemplate().query(
                "select * from account where id = ?",
                new BeanPropertyRowMapper<Account>(Account.class), accountId);
        return accounts.isEmpty() ? null : accounts.get(0);
    }

    @Override
    public Account findAccountByName(String accountName) {
        List<Account> accounts = super.getJdbcTemplate().query("select * from account where name = ?",new BeanPropertyRowMapper<Account>(Account.class),accountName);
        if(accounts.isEmpty()){
            return null;
        }
        if(accounts.size()>1){
            throw new RuntimeException("結果集不唯一");
        }
        return accounts.get(0);
    }

    @Override
    public void updateAccount(Account account) {
        super.getJdbcTemplate().update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
    }

}

2 Service

  • 接口
public interface IAccountService {
    
    Account findAccountById(Integer accountId);
    
    void transfer(String sourceName,String targetName,Float money);
    
}
  • 實現類
/**
 * 賬戶的業務層實現類
 * <p>
 * 事務控制應該都是在業務層
 */
public class AccountServiceImpl implements IAccountService {

    private IAccountDao accountDao;

    public void setAccountDao(IAccountDao accountDao) {
        this.accountDao = accountDao;
    }

    @Override
    public Account findAccountById(Integer accountId) {
        return accountDao.findAccountById(accountId);

    }

    @Override
    public void transfer(String sourceName, String targetName, Float money) {
        System.out.println("transfer....");
        //2.1根據名稱查詢轉出賬戶
        Account source = accountDao.findAccountByName(sourceName);
        //2.2根據名稱查詢轉入賬戶
        Account target = accountDao.findAccountByName(targetName);
        //2.3轉出賬戶減錢
        source.setMoney(source.getMoney() - money);
        //2.4轉入賬戶加錢
        target.setMoney(target.getMoney() + money);
        //2.5更新轉出賬戶
        accountDao.updateAccount(source);

        int i = 1 / 0;

        //2.6更新轉入賬戶
        accountDao.updateAccount(target);
    }
}

3 bean.xml

<?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:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       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/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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"> <!-- bean definitions here -->

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

    <bean id="accountDao" class="com.tzb.dao.impl.AccountDaoImpl">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--配置數據源-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring5?userSSL=false"></property>
        <property name="user" value="root"></property>
        <property name="password" value="root"></property>
    </bean>

    <!--sprig中基於 xml 聲明式事務控制 步驟
        1.配置事務管理器
        2.配置事務的通知
            此時需要導入事務的約束、tx名稱空間和約束,同時也需要 AOP
             tx:advice 標籤配置事務通知
                屬性: id 給事務起一個唯一的標誌
                       transaction-manager 給事務通知提供事務管理器引用
        3.配置 AOP 中的通用切入點表達式
        4.建立事務通知和切入點表達式的對應關係
        5.配置事務屬性
            在事務的通知 tx:advice 標籤內配置
    -->

    <!--配置事務管理器-->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--配置事務通知-->
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <!--配置事務屬性
            isolation:指定事務的隔離級別,默認是 DEFAULT,表示使用數據庫的默認隔離級別
            propagation: 傳播行爲,默認是 REQUIRED,表示一定會有事務,增刪改的選擇,查詢可以選擇 SUPPORTS
            read-only: 只有查詢方法才能設置爲 true。默認是 false,表示讀寫
            timeout: 事務超市時間,默認值是 -1,表示永不超時。如果指定了數值,默認是秒。

            rollback-for: 指定一個異常,當產生該異常時,事務回滾。產生其他異常,事務不回滾。沒有默認值,
                            表示任何異常都回滾

            no-rollback-for : 指定一個異常,當產生該異常時,事務不會滾。產生其他異常時,事務回滾。
                            沒有默認值,表示任何異常都回滾
        -->
        <tx:attributes>
            <tx:method name="transfer" propagation="REQUIRED" read-only="false"/>
            <tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
        </tx:attributes>
    </tx:advice>
    
    <!--配置 aop-->
    <aop:config>
        <!--配置切入點表達式-->
        <aop:pointcut id="pt1" expression="execution(* com.tzb.service.impl.*.*(..))"/>

        <!--建立切入點表達式和事務通知的對應關係-->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor>
    </aop:config>

</beans>

3.1 單元測試

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountServiceTest {

    @Autowired
    private IAccountService as;

    @Test
    public void testTransfer(){
        as.transfer("Mike","Jenny",100f);
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章