AspectTest.java 3 KB
package com.cjs.cms.biz;

import javax.annotation.Resource;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

import com.cjs.cms.dao.ration.TrustApplyDao;
import com.cjs.cms.dao.user.EntrustDataDao;
import com.cjs.cms.model.entrust.EntrustDataInfo;

/**
 * 多数据源测试。使用spring声明式事务时,在一个事务期间,spring不会重新获取Connection,导致事务内切换数据源失败。
 * 临时的方案是使用编程式事务,手动管理事务。
 * 
 * @author tongyufu
 *
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/applicationContext.xml")
public class AspectTest {

    private Logger              log = LogManager.getLogger();
    @Autowired
    private TrustApplyDao       trustApplyDao;
    @Autowired
    private EntrustDataDao      entrustDataDao;
    @Resource(name = "oracleTransactionTemplate")
    private TransactionTemplate oracleTransactionTemplate;
    @Resource(name = "mySqlTransactionTemplate")
    private TransactionTemplate mySqlTransactionTemplate;

    //@Test
    public void testTransaction() {
        final int total = trustApplyDao.searchTotal(null);
        EntrustDataInfo entrustDataInfo = oracleTransactionTemplate
            .execute(new TransactionCallback<EntrustDataInfo>() {

                @Override
                public EntrustDataInfo doInTransaction(TransactionStatus status) {
                    EntrustDataInfo data = new EntrustDataInfo();
                    data.setId(37);
                    data.setContent("内容1");
                    entrustDataDao.addContent(data);
                    log.info(total);
                    System.out.println(1 / 0);
                    return data;
                }
            });
        log.info(entrustDataInfo);
    }

    //@Test
    public void testTransactionWithoutResult() {
        mySqlTransactionTemplate.execute(new TransactionCallbackWithoutResult() {

            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                EntrustDataInfo data = new EntrustDataInfo();
                data.setId(37);
                data.setContent("内容2");
                entrustDataDao.addContent(data);
            }
        });

        oracleTransactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                trustApplyDao.searchTotal(null);
            }
        });
    }

}