package org.jim.server.util;

import com.jfinal.plugin.activerecord.DbKit;

import java.sql.SQLException;

public class TransactionKit {

    /**
     * 开始事务
     * @throws SQLException
     */
    public static void beginTransation() throws SQLException{
        DbKit.getConfig().setThreadLocalConnection(DbKit.getConfig().getConnection());
        DbKit.getConfig().getThreadLocalConnection().setAutoCommit(false);
    }

    /**
     * 开始事务
     * @param configName
     * @throws SQLException
     */
    public static void beginTransation(String configName) throws SQLException {
        DbKit.getConfig(configName).setThreadLocalConnection(DbKit.getConfig().getConnection());
        DbKit.getConfig(configName).getThreadLocalConnection().setAutoCommit(false);
    }

    /**
     * 事务回滚
     * @throws SQLException
     */
    public static void rollback() throws SQLException {
        DbKit.getConfig().getThreadLocalConnection().rollback();
        DbKit.getConfig().getThreadLocalConnection().setAutoCommit(true);
        DbKit.getConfig().removeThreadLocalConnection();
    }

    /**
     * 事务回滚
     * @param configName
     * @throws SQLException
     */
    public static void rollback(String configName) throws SQLException {
        DbKit.getConfig(configName).getThreadLocalConnection().rollback();
        DbKit.getConfig(configName).getThreadLocalConnection().setAutoCommit(true);
        DbKit.getConfig(configName).removeThreadLocalConnection();
    }

    /**
     * 事务提交
     * @throws SQLException
     */
    public static void commit() throws SQLException {
        DbKit.getConfig().getThreadLocalConnection().commit();
        DbKit.getConfig().getThreadLocalConnection().setAutoCommit(true);
        DbKit.getConfig().removeThreadLocalConnection();
    }

    /**
     * 事务提交
     * @param configName
     * @throws SQLException
     */
    public static void commit(String configName) throws SQLException {
        DbKit.getConfig(configName).getThreadLocalConnection().commit();
        DbKit.getConfig(configName).getThreadLocalConnection().setAutoCommit(true);
        DbKit.getConfig(configName).removeThreadLocalConnection();
    }



}
