JPA标准查询,订购课程 [英] JPA criteria query, order on class

查看:90
本文介绍了JPA标准查询,订购课程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JPA条件查询是否可以在课程上订购?想象以下域对象:

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 { ... }

使用常规的QL我能够做到

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实现:Hibernate-EntityManager v3.5.5-Final

JPA implementation used: Hibernate-EntityManager v3.5.5-Final

推荐答案

JPA 2.0引入了一个新的TYPE表达式,该表达式允许查询根据类类型限制结果.

JPA 2.0 introduces a new TYPE expression that allow a query to restrict results based on class types.

您可以使用Path#type()在Criteria API中使用类型表达式.因此,您可以尝试:

You can use a type expression with the Criteria API using Path#type(). So you could try:

CriteriaQuery criteriaQuery = builder.createQuery(Hobby.class);
Root hobbyRoot = criteriaQuery.from(Hobby.class);
criteriaQuery.orderBy(builder.asc(hobbyRoot.type());
List hobbies = entityManager.createQuery(criteriaQuery).getResultList();

虽然此代码可以编译,但我没有对其进行测试(明天将尝试).

While this code compiles, I didn't test it (I'll give it a try tomorrow).

实际上,我想知道这是否合法,或者type()是否应该作为select的一部分才能进行order by(也许这就是标准查询应该生成的内容).需要检查一下.

Actually, I wonder if this is legal or if the type() should be part of the select in order to order by it (maybe that's what the criteria query is supposed to generate). Need to check that.

  • JPA 2.0规范
    • 第4.6.17.4节实体类型表达式"
    • JPA 2.0 specification
      • Section 4.6.17.4 "Entity Type Expressions"

      这篇关于JPA标准查询,订购课程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆