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.com.agendamento.model.daos; import java.sql.Connection; import java.sql.SQLException; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.engine.jdbc.spi.JdbcConnectionAccess; import org.hibernate.engine.spi.SessionImplementor; /** * * @author Celio Matos */ public abstract class AbstractFacade<T> { @PersistenceContext(unitName = "AgendamentoPU") private EntityManager em; private final Class<T> entityClass; Connection conn = null; public AbstractFacade(Class<T> entityClass) { this.entityClass = entityClass; } protected EntityManager getEntityManager() { return em; } protected Query executeHql(String hql) { return getEntityManager().createQuery(hql); } protected Query executeSql(String sql) { return getEntityManager().createNativeQuery(sql); } public void create(T entity) { getEntityManager().persist(entity); } public void edit(T entity) { getEntityManager().merge(entity); } public void remove(T entity) { getEntityManager().remove(getEntityManager().merge(entity)); } public T find(Object id) { return getEntityManager().find(entityClass, id); } public Connection getConnection() throws SQLException { Session session = em.unwrap(Session.class); SessionFactory sf = session.getSessionFactory(); SessionImplementor si = (SessionImplementor) sf.getCurrentSession(); JdbcConnectionAccess access = si.getJdbcConnectionAccess(); return access.obtainConnection(); } }