0

For example, I have a base entity called 'MyEntityParent' and two sub types 'ZChild' and 'AChild'.

When using the following HQL, this will sort the result list by the type's internal integer value (same as the special class property):

select e from MyEntityParent e
order by type(e)

However, I need to sort the result list by their entity type's name. I.e., first, instances of type 'AChild', then, instances of type 'ZChild'.

4

2 回答 2

0

尝试

select e from MyEntityParent e order by e.class

从休眠 3.6 文档:

在多态持久性的情况下,特殊属性类访问实例的鉴别器值。嵌入在 where 子句中的 Java 类名将被转换为它的鉴别器值。

http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/queryhql.html#queryhql-where

但这在 Hibernate 4.1 中已被弃用

如果我正确阅读文档,这也不完全是您的愿望,因为它返回鉴别器值,而不是确切的类型名称。

于 2013-02-18T13:08:06.070 回答
0

没有直接的解决方案,因为 HQL 被转换为 SQL 并且数据库不知道值如何映射到类的名称。有办法做到这一点,但它并不好:

  • 查询变得复杂,因为我们必须在查询中定义顺序。
  • 选择列表包含定义顺序的附加值,因此我们无法返回实体列表。
  • 当模型更改时,应修改查询

查询是:

SELECT e,
  CASE TYPE(e) WHEN AChild THEN 1
               WHEN ZChild THEN 2
               ELSE 3 
  END AS orderValue
FROM MyEntityParent e ORDER BY orderValue 

如前所述,结果不再是实体列表,而是对象数组列表,因此访问实体更加困难。实体本身是数组中的第一项(索引 0),第二项是 ordedValue:

 List<Object[]> result = em.createQuery("JPQL given above").getResultList();
 for (Object[] resultRow : result) {
     MyEntityParent myEntityParent = (MyEntityParent) resultRow[0];
 }

解决方案是有效的 JPQL,因此它不是特定于 Hibernate,但也适用于其他 JPA 提供程序。

于 2013-02-19T20:55:50.707 回答