package com.brilliance.mda.runtime.mda.impl;

import com.brilliance.mda.runtime.mda.driver.MdaEnv;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

public abstract class AbstractDaoSession {
    private DataSourceTransactionManager transactionManager;
    private ThreadLocal<TransactionStatus> status = new ThreadLocal<TransactionStatus>();

    public AbstractDaoSession() {

    }

    private DataSourceTransactionManager getTransactionManager() {
        if (transactionManager == null)
            transactionManager = MdaEnv.getBean(DataSourceTransactionManager.class);
        return transactionManager;
    }

    public void dbBegin() {
		if(isOpenTrans()) //事务为提交，回滚
			this.dbRollback();
		DefaultTransactionDefinition def = new DefaultTransactionDefinition();
		def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
		status.set(getTransactionManager().getTransaction(def));
    }

    public void dbCommit() {
		if(isOpenTrans())
		{
			getTransactionManager().commit(status.get());
			status.remove();
		}
    }

    public void dbRollback() {
		if(isOpenTrans())
		{
			getTransactionManager().rollback(status.get());
			status.remove();
		}
        new RuntimeException("业务处理错误，手动rollback");
    }

    public boolean isOpenTrans() {
		return status.get() != null;
        //return false;
    }
}
