Question

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

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

The query is very shorthand - and I can't find the rules for what is optional and what isn't in any of the guides. Is this brevity acceptable?

Secondly, I want to now implement this in a generic DAO, something such as:

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

How can I rewrite the first query to work for all types as I can't hardcode the "from Category"..?

Was it helpful?

Solution

  1. Yes, the brevity is acceptable. Although I prefer the full syntax because it is more "appealing" to others who have more SQL experience.

  2. You have to add a Class<E> parameter to your DAO:

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

OTHER TIPS

You actually don't have to use a method parameter, but can use Reflection.

Example Code using 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];
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top