JPQL SELECT query optional + general DAO selection

I followed a working JPA example to retrieve category objects as such:

return (ArrayList<Category>) getEntityManager().createQuery("from Category").getResultList();

The request is very short - and I cannot find the rules for what is optional and what is not in any of the manuals. Is this brevity acceptable?

Secondly, I want to implement this in a general DAO, for example:

public interface DAO<E, K>
{
    List<E> getAll();
}

How can I rewrite the first query to work for all types, since I can’t hardcode "from the category" ..?

+3
source share
2 answers
  • Yes, brevity is acceptable. Although I prefer the full syntax because it is more “attractive” to others who have more SQL experience.

  • Class<E> DAO:

    public List<E> getAll(Class<E> entityClass) {
         Query query = enittyManager.createQuery("from " + entityClass.getName());
         query.getResultList();
    }
    
+5

, Reflection.

Reflection

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class<T> DAO {         
    protected Class<T> clazz;

    public DAO()
    {
      Type genericSuperclass = getClass().getGenericSuperclass();
      // Allow this class to be safely instantiated with or without a parameterized type
      if (genericSuperclass instanceof ParameterizedType)
        clazz = (Class<T>) ((ParameterizedType) genericSuperclass).getActualTypeArguments()[0];
    }
}
+2

Source: https://habr.com/ru/post/1732979/


All Articles