Ao criar uma (Classe JPA Controlador) … criada automáticamente… na minha classe DAO… fiz algumas modificações…
transformando ela em Genérica…
A Classe correspondeu !! - Gostaria do ponto de vista de vcs… valeu…
public class Dao<T> implements Serializable{
private EntityManagerFactory emf = null;
public Dao(){
this.emf = Persistence.createEntityManagerFactory("PadariaPU");
}
public EntityManager getEntityManager(){
return emf.createEntityManager();
}
public void create(T obj){ //ok
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
em.persist(obj);
em.getTransaction().commit();
}finally{
if (em != null){
em.close();
}
}
}
public void edit(T obj, int id, Class<T> classe) throws Exception{ //ok
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
obj = em.merge(obj);
em.getTransaction().commit();
}catch(Exception ex){
String msg = ex.getLocalizedMessage();
if(msg == null || msg.length() == 0){
if(findObject(id, classe) == null){
throw new Exception("The clientes with id " + id + " no longer exists.");
}
}
throw ex;
}finally{
if(em != null){
em.close();
}
}
}
public void destroy(int id, Class<T> classe) throws Exception{ //ok
EntityManager em = null;
try{
em = getEntityManager();
em.getTransaction().begin();
try{
em.remove(em.getReference(classe, id));
}catch(EntityNotFoundException enfe){
throw new Exception("The clientes with id " + id + " no longer exists.", enfe);
}
em.getTransaction().commit();
}finally{
if(em != null){
em.close();
}
}
}
public List<T> findEntities(Class<T> classe){ //ok
return findEntities(true, -1, -1, classe);
}
public List<T> findEntities(int maxResults, int firstResult, Class<T> classe){ //ok
return findEntities(false, maxResults, firstResult, classe);
}
private List<T> findEntities(boolean all, int maxResults, int firstResult, Class<T> classe){ //ok
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
cq.select(cq.from(classe));
Query q = em.createQuery(cq);
if (!all) {
q.setMaxResults(maxResults);
q.setFirstResult(firstResult);
}
return q.getResultList();
} finally {
em.close();
}
}
public T findObject(int id, Class<T> classe){ //ok
EntityManager em = getEntityManager();
try {
return em.find(classe, id);
} finally {
em.close();
}
}
public int getClientesCount(Class<T> classe){ //ok
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
Root<T> rt = cq.from(classe);
cq.select(em.getCriteriaBuilder().count(rt));
Query q = em.createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
} finally {
em.close();
}
}
}