Hibernate esta deixando conexão aberta

2 respostas
carlos_chea

tudo bem pessoal???

o meu problema é o requinte, quando um usuário entra no meu sistema, o java abre uma conexão e não fecha, estou utilizando singleton na criação da fabrica…
como eu fecho a minha EntityManagerFactory???

Fabrica:

import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class FactoryDao {
    
private static FactoryDao singleton;	

        private EntityManagerFactory emf = null;
	
	static {
		singleton = new FactoryDao();
	}
	
	private FactoryDao() {
		emf = Persistence.createEntityManagerFactory("testePU");
	}	
	
	public EntityManagerFactory criarEntityManagerFactory() {
		return emf;
	}
	
	public static FactoryDao getInstance(){
		return singleton;
	}
}

Dao

import br.com.corretora.model.Banco;
import br.com.corretora.service.BancoService;
import hibernate.corretora.service.exceptions.NonexistentEntityException;

import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.Persistence;
import javax.transaction.UserTransaction;

import org.springframework.stereotype.Service;



@Service
public class BancoDao implements Serializable, BancoService {

	public BancoDao(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    public BancoDao() {
        //this.emf = Persistence.createEntityManagerFactory("corretoraPU");
        this.emf = FactoryDao.getInstance().criarEntityManagerFactory();
    }
    
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

	@Override
	public void criar(Banco banco) {
		EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            em.persist(banco);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
	}

	@Override
	public void editar(Banco banco) throws NonexistentEntityException,
			Exception {
		EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            banco = em.merge(banco);
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Long id = banco.getId();
                if (mostraBanco(id) == null) {
                    throw new NonexistentEntityException("O banco com id " + id + " não existe.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
		
	}

	@Override
	public void remover(Long id) throws NonexistentEntityException {
		EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Banco banco;
            try {
            	banco = em.getReference(Banco.class, id);
            	banco.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("O banco com id " + id + " não existe.", enfe);
            }
            em.remove(banco);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
		
	}

	@Override
	public List<Banco> listarBancos() {
		return listarBancos(true, -1, -1);
	}

	@Override
	public List<Banco> listarBancos(int maxResults, int firstResult) {
		return listarBancos(false, maxResults, firstResult);
	}

	@Override
	public List<Banco> listarBancos(boolean all, int maxResults, int firstResult) {
		EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select object(o) from Banco as o");
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
	}

	@Override
	public Banco mostraBanco(Long id) {
		EntityManager em = getEntityManager();
        try {
            return em.find(Banco.class, id);
        } finally {
            em.close();
        }
	}

	@Override
	public int getBancoCount() {
		EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select count(o) from Banco as o");
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
	}

	

	
    
}

2 Respostas

romarcio

Mas você não deve fechar a EntityManagerFactory a cada novo acesso. É por isso que é chamado de fabrica, você cria apenas uma e ela então te da acesso a varios EntityManager, e são estes que devem ser fechados após o uso. Como você fez no seu código da classe BancoDao.

carlos_chea

Então o código esta certo né??

Criado 30 de setembro de 2012
Ultima resposta 30 de set. de 2012
Respostas 2
Participantes 2