Giullia
What you are looking for is a generic DAO to be reused with several entities, follow 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 use your methods as long as you have an EntityManager to pass.
If it is possible to inject EntityManager with EJB or CDI, even better.