我正在尝试使以下NamedQuery
工作:
@NamedQuery(name="MyEntity.findByUser", query="SELECT m FROM MyEntity m WHERE m.owner = :user OFFSET :offset LIMIT :limit")
问题是,这会导致Hibernate在服务器启动时出现以下堆栈跟踪:
[INFO] [talledLocalContainer] java.lang.NullPointerException
[INFO] [talledLocalContainer] at org.hibernate.hql.ast.ParameterTranslationsImpl.getNamedParameterExpectedType(ParameterTranslationsImpl.java:63)
[INFO] [talledLocalContainer] at org.hibernate.engine.query.HQLQueryPlan.buildParameterMetadata(HQLQueryPlan.java:296)
[INFO] [talledLocalContainer] at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:97)
[INFO] [talledLocalContainer] at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:56)
[INFO] [talledLocalContainer] at org.hibernate.engine.query.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:72)
[INFO] [talledLocalContainer] at org.hibernate.impl.SessionFactoryImpl.checkNamedQueries(SessionFactoryImpl.java:400)
[INFO] [talledLocalContainer] at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryImpl.java:351)
[INFO] [talledLocalContainer] at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1291)
[INFO] [talledLocalContainer] at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:713)
[INFO] [talledLocalContainer] at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:121)
[INFO] [talledLocalContainer] at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:83)
[INFO] [talledLocalContainer] at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:60)
(...)
经过反复试验,我发现用文字值(分别为0和10(替换":offset"one_answers":limit"效果很好。这是有原因的吗?有没有办法让命名参数在我的查询中工作?
我看到了一些其他示例,它们使用定位参数来动态设置命名查询中的偏移量和限制值,但我不希望我的代码退化为一堆不可读的query.setParameter(1, "someValue");
废话。命名参数本应消除这种垃圾代码。
Hibernate有一个特殊的API,用于在运行时指定这些概念。试试这个:
@NamedQuery(name="MyEntity.findByUser",
query="SELECT m FROM MyEntity m WHERE m.owner = :user") // don't put OFFSET or LIMIT here
...
entityManager.createNamedQuery("MyEntity.findByUser")
.setFirstResult(20) // equivalent to OFFSET
.setMaxResults(5) // equivalent to LIMIT
.getResultList();
我想这样做的原因是,数据库供应商在SQL查询中如何以及在哪里指定这些概念方面差异很大,所以选择一种格式而不是另一种格式是不合理的,而且很难在它们之间进行转换。
这样,方言实现就清楚地知道需要做什么,然后就可以做了