how would that generic listAll() look?

Asked

Viewed 176 times

0

I have the following class/method

public class DAO<T>{
    EntityManager entityManager = (...)
    public List<T> listAll(String jpql){
        return entityManager.createQuery(jpql).getResultList();
    }
}

works, but he’s not making use of the Generics, the string passed as parameter works as a gambiarra.

How do I get the whole Class past us Generics make a select with the JPQL?

Something like this...

public class DAO<T>{
    EntityManager entityManager = (...)
    public List<T> listAll(String jpql){
        return (List T)entityManager.createQuery("select t from T t).getResultList();
    }
}

Error is thrown saying that T is not mapped, really has no way to know what is the T, but how would then this query using the Generics? Thank you!

  • You don’t necessarily need to pass JPQL to the method, since you already know which one T is being used through getClass().getEnclosingClass().getSimpleName(). You can then create the query within the listAll without passing any parameter.

1 answer

2


Take the class as a parameter in the method and pass to select.

public List<T> listAll(Class<T> clazz){
    return (List<T>) entityManager.createQuery("select t from " + clazz.getName() + " t").getResultList();

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.