Typed Query in Entity Manager, the generic way

34 Views Asked by At

I read this article: https://www.baeldung.com/simplifying-the-data-access-layer-with-spring-and-java-generics

And i have a question for this code:

@SuppressWarnings("unchecked")
    public List<T> findAll() {
        return entityManager.createQuery("from " + clazz.getName()).getResultList();
    }

For me here the List should be more replaced with List<?> because the type checking here is not really done. But there exists a derived TypedQuery also, so why not use this instead? Could this code not written as:

@SuppressWarnings("unchecked")
    public List<T> findAll() {
        return entityManager.createQuery("from " + clazz.getName(), clazz).getResultList();
    }

To use the TypedQuery and then really get the List a result?

The other question is the term "from " + clazz.getName()) itself. Am I right, this is just a short form without the Select? I would have written this:

@SuppressWarnings("unchecked")
    public List<T> findAll() {
        return entityManager.createQuery("Select t from " + clazz.getName() + " t", clazz).getResultList();
    }

I could not find anything about this form, just starting with a "from ..." In the literature I use for research, there was always a

createQuery("Select ....") etc,

I tried my code examples above and for me it looked like it works... just want to get more information on this case. Maybe im on the wrong way?

0

There are 0 best solutions below