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.crescer.aula04.entity.dao; import br.crescer.aula04.entity.nunes.Cidade; import java.io.Serializable; import java.lang.reflect.ParameterizedType; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.criterion.Restrictions; /** * * @author lucas.lentz */ public abstract class GenericDAO<T> implements DAO<T> { private Session session; private Criteria criteria; final EntityManagerFactory emf = Persistence.createEntityManagerFactory("CRESCER16"); final EntityManager em = emf.createEntityManager(); @Override public T listById(Serializable id) { this.session = em.unwrap(Session.class); this.criteria = session.createCriteria(this.getClass()); return (T) this.session.load(getGeneric(), id); // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void insert(T t) { Session s = em.unwrap(Session.class); s.save(t); // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void remove(long id) { Session s = em.unwrap(Session.class); T t = listById(id); s.delete(t); // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public List<T> listAll() { this.session = em.unwrap(Session.class); this.criteria = session.createCriteria(getGeneric()); return this.criteria.list(); // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public List<T> search(String sch) { this.session = em.unwrap(Session.class); this.criteria = session.createCriteria(getGeneric()); this.criteria.add(Restrictions.like("nome", sch)); return this.criteria.list(); // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } public abstract Class<?> getGeneric(); }