Giullia
What you’re looking for is a generic DAO to be reused with multiple entities, here’s an example
public class DAOGenerico<T> {
private EntityManager manager;
public DAOGenerico(EntityManager manager) {
this.manager = manager;
}
public T getById(Class<T> clazz, Long id) {
return manager.find(clazz, id);
}
public void save(T entity) {
manager.getTransaction().begin();
manager.persist(entity);
manager.getTransaction().commit();
}
public void update(T entity) {
manager.getTransaction().begin();
manager.merge(entity);
manager.getTransaction().commit();
}
public void delete(T entity) {
manager.getTransaction().begin();
manager.remove(entity);
manager.getTransaction().commit();
}
public List<T> findAll(Class<T> type) {
CriteriaBuilder criteriaBuilder = manager.getCriteriaBuilder();
CriteriaQuery<T> query = criteriaBuilder.createQuery(type);
Root<T> root = query.from(type);
CriteriaQuery<T> select = query.select(root);
TypedQuery<T> all = manager.createQuery(select);
return all.getResultList();
}
}
Any other class you inherit from this Daogenerico will be able to make use of your methods, as long as you have an Entitymanager to pass.
If you can inject Entitymanager with EJB or CDI, even better.
Giullia, what do you mean by JPA Container? This is from some specific framework?
– Ricardo Rodrigues de Faria