package online.jpa.producer;

import javax.enterprise.context.Dependent;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Disposes;
import javax.enterprise.inject.Produces;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import online.jpa.extension.ProxyEntityManager;
import online.jpa.extension.ExEntityManager;

/**
 * CDI供給用
 *
 * @author Tadashi Nakayama
 */
@Dependent
public final class EntityManagerProducer {

    /** EntityManagerFactory */
    private static final EntityManagerFactory EMF;

    static {
        EMF = Persistence.createEntityManagerFactory("defaultUnit");
    }

    /**
     * EntityManager作成
     *
     * @return EntityManager
     */
    @Produces
    @RequestScoped
    public ExEntityManager create() {
        return new ProxyEntityManager(EMF.createEntityManager());
    }

    /**
     * EntityManagerクローズ
     *
     * @param entityManager EntityManager
     */
    public void closeEntityManager(@Disposes final EntityManager entityManager) {
        if (entityManager.isOpen()) {
            entityManager.close();
        }
    }
}
