/*
 * Created on: Dec 17, 2004
 * Author: Dibyendu Majumdar
 */
package com.ponl.framework.dao.ibatis;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import com.ibatis.dao.client.DaoException;

/**
 * <p>
 * GenericDaoTransaction:
 * </p>
 * 
 * <pre>
 *  History:
 *  Dec 17, 2004 DM Created
 * </pre>
 * 
 * @author Dibyendu Majumdar
 * @version
 * @since TCA 3.0
 */
public class GenericDaoTransaction implements
        com.ibatis.dao.engine.transaction.ConnectionDaoTransaction {

    private Connection connection;

    private boolean globalCommit = false;

    public GenericDaoTransaction(DataSource dataSource, boolean globalCommit) {
        this.globalCommit = globalCommit;
        try {
            connection = dataSource.getConnection();
            if (connection == null) {
                throw new DaoException(
                        "Could not start transaction.  Cause: The DataSource returned a null connection.");
            }
            if (connection.getAutoCommit()) {
                connection.setAutoCommit(false);
            }
        } catch (SQLException e) {
            throw new DaoException("Error starting JDBC transaction.  Cause: "
                    + e, e);
        }
    }

    public void commit() {
        if (globalCommit)
            return;
        try {
            try {
                connection.commit();
            } finally {
                connection.close();
            }
        } catch (SQLException e) {
            throw new DaoException(
                    "Error committing JDBC transaction.  Cause: " + e, e);
        }
    }

    public void rollback() {
        if (globalCommit)
            return;
        try {
            try {
                connection.rollback();
            } finally {
                connection.close();
            }
        } catch (SQLException e) {
            throw new DaoException("Error ending JDBC transaction.  Cause: "
                    + e, e);
        }
    }

    public Connection getConnection() {
        return connection;
    }
}