Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package br.genericrepository.util; import com.mysql.jdbc.Connection; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import org.hibernate.Session; import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; import org.hibernate.engine.spi.SessionFactoryImplementor; /** * @brief Classe ManagerFactory * @author Kaynan Coelho Lira * @date 27/12/2015 */ public class ManagerFactory { private static ManagerFactory managerFactory; private EntityManagerFactory emf; private EntityManager em; public ManagerFactory() { emf = Persistence.createEntityManagerFactory(ConfigDataSource.persistenceUnit); em = emf.createEntityManager(); } public static synchronized ManagerFactory getInstante() { if (managerFactory == null) { managerFactory = new ManagerFactory(); } return managerFactory; } public void openConnection() { emf = Persistence.createEntityManagerFactory(ConfigDataSource.persistenceUnit); em = emf.createEntityManager(); } public void closeConnection() { em.close(); emf.close(); } public Connection getConnection() { Connection connection = null; try { Session session = (Session) em.getDelegate(); SessionFactoryImplementor sfi = (SessionFactoryImplementor) session.getSessionFactory(); ConnectionProvider cp = sfi.getConnectionProvider(); connection = (Connection) cp.getConnection(); return connection; } catch (Exception ex) { ex.printStackTrace(); } return connection; } public EntityManagerFactory getEmf() { return emf; } public void setEmf(EntityManagerFactory emf) { this.emf = emf; } public EntityManager getEm() { return em; } public void setEm(EntityManager em) { this.em = em; } }