diff --git a/Conexion.java b/Conexion.java new file mode 100644 index 0000000..ef0eb8c --- /dev/null +++ b/Conexion.java @@ -0,0 +1,87 @@ +package util; + +import java.util.List; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; +import javax.persistence.TypedQuery; + + + +public class Conexion { + private Class c; + private static EntityManager em = null; + + public Conexion() { + em = this.getEm(); + } + + public Conexion(Class c) { + em = this.getEm(); + this.c = c; + } + + public void setC(Class c){ + this.c = c; + } + + public static EntityManager getEm(){ + if ( em == null ) { + EntityManagerFactory emf = Persistence.createEntityManagerFactory("makabi"); + em = emf.createEntityManager(); + } + return em; + } + + public T find(E id){ + T object = (T) em.find(c, id); + return object; + } + + public List list(){ + TypedQuery consulta= em.createNamedQuery(c.getSimpleName()+".findAll", c); + List lista = (List) consulta.getResultList(); + return lista; + } + + + public void insert(T o){ + try { + em.getTransaction().begin(); + em.persist(o); + em.getTransaction().commit(); + } catch (Exception e) { + e.printStackTrace(); + }finally { + //em.close(); + } + + } + + public void update(T o){ + try { + em.getTransaction().begin(); + em.merge(o); + em.getTransaction().commit(); + } catch (Exception e) { + e.printStackTrace(); + }finally { + //em.close(); + } + + } + + public void delete(T o){ + try { + em.getTransaction().begin(); + em.remove(o); + em.getTransaction().commit(); + } catch (Exception e) { + e.printStackTrace(); + }finally { + // em.close(); + } + + } +}