tags:

views:

149

answers:

1

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"..?

+1  A: 
  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();
    }
    
Bozho
thanks for the tip, I am getting the classname in the generic dao's constructor and using that variable in the query!
Mobs
@Mobs fine :) btw, accepted answers with 0 upvotes look weird ;)
Bozho