JPA条件查询、类排序
有没有一种方法可以使用 JPA 标准查询来对 class 进行排序?想象一下以下域对象:
abstract class Hobby { ... }
class Coding extends Hobby { ... }
class Gaming extends Hobby { ... }
使用常规 QL 我能够执行
from Hobby h order by h.class
但当我在条件查询上应用相同的逻辑时,会发生运行时异常“未知属性”。
CriteriaQuery<Hobby> criteriaQuery = builder.createQuery(Hobby.class);
Root<Hobby> hobbyRoot = criteriaQuery.from(Hobby.class);
criteriaQuery.orderBy(builder.asc(hobbyRoot.get("class"));
List<Hobby> hobbies = entityManager.createQuery(criteriaQuery).getResultList();
使用的 JPA 实现:Hibernate-EntityManager v3.5.5-Final
Is there a way with JPA criteria queries to order on class? Imagine the following domain objects:
abstract class Hobby { ... }
class Coding extends Hobby { ... }
class Gaming extends Hobby { ... }
Using regular QL I was able to do
from Hobby h order by h.class
But when I apply the same logic on a criteria query, the runtime exception "unknown attribute" occurs.
CriteriaQuery<Hobby> criteriaQuery = builder.createQuery(Hobby.class);
Root<Hobby> hobbyRoot = criteriaQuery.from(Hobby.class);
criteriaQuery.orderBy(builder.asc(hobbyRoot.get("class"));
List<Hobby> hobbies = entityManager.createQuery(criteriaQuery).getResultList();
JPA implementation used: Hibernate-EntityManager v3.5.5-Final
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
JPA 2.0 引入了新的
TYPE
表达式,允许查询根据类类型限制结果。您可以使用
Path#type()
将类型表达式与 Criteria API 结合使用。所以你可以尝试:当这段代码编译时,我没有测试它(明天我会尝试一下)。
实际上,我想知道这是否合法,或者
type()
是否应该成为选择的一部分,以便对其进行order by
(也许这就是条件查询应该做的事情)产生)。需要检查一下。参考
更多资源
JPA 2.0 introduces a new
TYPE
expression that allow a query to restrict results based on class types.You can use a type expression with the Criteria API using
Path#type()
. So you could try:While this code compiles, I didn't test it (I'll give it a try tomorrow).
Actually, I wonder if this is legal or if the
type()
should be part of the select in order toorder by
it (maybe that's what the criteria query is supposed to generate). Need to check that.References
More resources