Reputation: 989
I want do a GenericDao pass by parameter Entity but I don´t know how to convert Entidad to Object. I tried put GenericDaoWithOrder<Entidad extends Object>
but does not work.
public abstract class GenericDao<Entidad> {
@PersistenceContext
private EntityManager em;
public List<Entidad> findAll(Integer start, Integer maxResult) {
TypedQuery<Entidad> query = em.createNamedQuery(Entidad.class.getCanonicalName() + ".findAll", Entidad.class);
query.setFirstResult(start);
query.setMaxResults(maxResult);
return query.getResultList();
}
}
Upvotes: 0
Views: 76
Reputation: 122364
In the code you've shown, Entidad
is a parameter, not a class name, so you can't refer to Entidad.class
. The usual way to resolve this kind of thing is to pass the Class
object representing the real class to the constructor of GenericDao
, e.g.
public abstract class GenericDao<E> {
@PersistenceContext
private EntityManager em;
private Class<E> clazz;
protected GenericDao(Class<E> clazz) {
this.clazz = clazz;
}
public List<E> findAll(Integer start, Integer maxResult) {
TypedQuery<E> query = em.createNamedQuery(clazz.getCanonicalName() + ".findAll", clazz);
query.setFirstResult(start);
query.setMaxResults(maxResult);
return query.getResultList();
}
}
(I've shortened the type parameter name to E
to make it clearer that it's a parameter rather than the name of a real class). Concrete subclasses then pass in the relevant Class
:
public class UserDao extends GenericDao<User> {
public UserDao() {
super(User.class);
}
}
Upvotes: 1