package org.academiadecodigo.bootcamp.fxlogin.persistence.jpa;

import org.academiadecodigo.bootcamp.fxlogin.persistence.TransactionManager;

/**
 * MIT License
 * (c) 2017 Ricardo Constantino
 */

public class JpaTransactionManager implements TransactionManager {
    private JpaSessionManager sm;

    public JpaTransactionManager(JpaSessionManager sm) {
        this.sm = sm;
    }

    @Override
    public void beginRead() {
        sm.startSession();
    }

    @Override
    public void beginWrite() {
        sm.getCurrentSession().getTransaction().begin();
    }

    @Override
    public void commit() {
        if (sm.getCurrentSession().getTransaction().isActive()) {
            sm.getCurrentSession().getTransaction().commit();
        }
        sm.stopSession();
    }

    @Override
    public void rollback() {
        if (sm.getCurrentSession().getTransaction().isActive()) {
            sm.getCurrentSession().getTransaction().rollback();
        }
        sm.stopSession();
    }



}
