编程语言
首页 > 编程语言> > 【Spring事务控制】编程式事务控制

【Spring事务控制】编程式事务控制

作者:互联网

事务控制模板类


通过实现接口:TransactionCallback action ,重写里面的doInTransaction方法,将切入点放入方法中,实现事务控制。


该模板类也需要在bean中配置TranscationManger。

样例

bean.xml

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

    <!--配置事务模板对象-->
    <bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
        <property name="transactionManager" ref="transactionManager"></property>
    </bean>

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

service

package com.czy.service.impl;

import com.czy.dao.AccountDao;
import com.czy.domain.Account;
import com.czy.service.AccountService;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

public class AccountServiceImpl implements AccountService {

    private AccountDao dao;

    private TransactionTemplate transactionTemplate;

    public void setTransactionTemplate(TransactionTemplate transactionTemplate) {
        this.transactionTemplate = transactionTemplate;
    }

    public void setDao(AccountDao dao) {
        this.dao = dao;
    }

    public Account findAccountById(Integer accountId) {
        return dao.findAccountById(accountId);
    }

    public void transfer(String sourceName, String targetName, Float money) {
        transactionTemplate.execute(new TransactionCallback<Object>() {
            @Override
            public Object doInTransaction(TransactionStatus transactionStatus) {
                Account source = dao.findAccountByName(sourceName);
                Account target = dao.findAccountByName(targetName);

                source.setMoney(source.getMoney() - money);

                dao.updateAccount(source);

                int i = 1/0;

                target.setMoney(target.getMoney() + money);

                dao.updateAccount(target);
                return null;
            }
        });

    }
}

标签:控制,事务,czy,Spring,dao,source,transactionTemplate,import,public
来源: https://www.cnblogs.com/czy-algorithm/p/16188754.html