如何将Query转换为NamedQuery?

时间:2014-01-10 11:11:56

标签: java hibernate

我无法将简单的Query转换为@NamedQuery。我错过了以下代码中的内容吗?

//works fine
em.createQuery("FROM Person p WHERE p.name = :name").setParameter("name", name).getResultList();

//throws exception
em.createQuery(Person.FIND_BY_ID).setParameter("name", name).getResultList();
@NamedQueries({
    @NamedQuery(
        name = BookingRequest.FIND_BY_ID,
        query = "FROM Person p WHERE p.name = :name"
    )
})
class Person {
    public static final String FIND_BY_ID = "Person.findById";
}

错误:

java.lang.IllegalArgumentException: node to traverse cannot be null!
    at org.hibernate.hql.internal.ast.util.NodeTraverser.traverseDepthFirst(NodeTraverser.java:65)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:274)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:182)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:138)
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:105)
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:80)
    at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:168)
    at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:222)
    at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:200)
    at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1703)
    at org.hibernate.ejb.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:291)

1 个答案:

答案 0 :(得分:0)

你应该使用

em.createNamedQuery("query name") ...