Last active
August 29, 2015 14:04
-
-
Save dilnei/f27e04f2bde0190fa526 to your computer and use it in GitHub Desktop.
DAO<T> (Dao genérico)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.Serializable; | |
import java.util.List; | |
import javax.persistence.EntityManager; | |
import javax.persistence.criteria.CriteriaQuery; | |
/** | |
* DAO genérico. | |
* | |
* @author Dilnei Cunha | |
*/ | |
public class DAO<T> implements Serializable { | |
private final Class<T> classe; | |
private EntityManager entityManager; | |
public DAO(Class<T> classe, EntityManager entityManager) { | |
this.classe = classe; | |
this.entityManager = entityManager; | |
} | |
public void adiciona(T t) { | |
entityManager.persist(t); | |
} | |
public void remove(T t) { | |
entityManager.remove(entityManager.merge(t)); | |
} | |
public void atualiza(T t) { | |
entityManager.merge(t); | |
} | |
public List<T> listaTodos() { | |
CriteriaQuery<T> query = entityManager.getCriteriaBuilder().createQuery(classe); | |
query.select(query.from(classe)); | |
List<T> lista = entityManager.createQuery(query).getResultList(); | |
return lista; | |
} | |
public T buscaPorId(Long id) { | |
return entityManager.find(classe, id); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment