开发者

javax.persistence.Query with Generics

I'm trying to implement a namedQuery (jav开发者_C百科ax.persistence.Query) with Generics. This is working for single objects:

public <T extends Status> T fStatusByCode(Class<T> type, String code)
{
    Query nq = getManager().createNamedQuery("f"+type.newInstance().getClass().getSimpleName());
    nq.setParameter("code", code);
    T result=(T)nq.getSingleResult();
    return result;
}

Unfortunately this can not directly applied to get all objects:

   public List<T extends UtilsStatus> allStatus(Class<T> type)
    {
        ...
        List<T> lResult = (List<T>)q.getResultList();
        return lResult;
    }

The extends in the method public List.... seems to be terrible wrong, but I don't get the picture. How is the syntax to get a List<T>?

Thank you, Thor


Use JPA 2 and it's EntityManager.createNamedQuery(jpql, Class) method. It returns a TypedQuery which is what you should use.


You have to declare the generic type before you use it in List:

public <T extends UtilsStatus> List<T> allStatus(Class<T> type)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜