如何解决此休眠限制? [英] How can I work-around this Hibernate Limitation?

查看:101
本文介绍了如何解决此休眠限制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在层次结构中有3个这样的实体:

I have 3 entities in a Hierarchy like this:

         MyInterface
              |
      -----------------
      |               |
   Entity1          Entity2

MyInterface不在Hibernate中映射(因为我正在使用隐式多态策略以映射此继承)

The MyInterface is NOT mapped in Hibernate (because I am using implicit polymorphism strategy to map this inheritance)

事实上,如果我启动这样的查询:

And, in fact, if I launch a query like this one:

"FROM MyInterface"

它工作得很好(因为它检索Entity1的所有实例和Entity2的所有实例,将它们放在一起,然后返回List<MyInterface>).

It works just fine (because it retrieves all the instances of Entity1 and all the instances of Entity2, puts them together, and returns a List<MyInterface>).

如果我们查看由Hibernate生成的SQL,它将启动2个独立的SQL查询,以首先检索Entity1实例,再启动另一个以检索Entity2实例,但是我对此表示满意.

If we look at the SQL generated by Hibernate, it is launching 2 independent SQL queries to first retrieve the Entity1 instances an another one to retrieve Entity2 instances, but I am fine with this.

当您尝试执行以下操作时,就会出现大问题:

The BIG problem comes when you try to do something like this:

"FROM MyInterface ORDER BY someField"

因为它将ORDER BY应用于第一个SQL查询,然后将相同的ORDER BY应用于第二个SQL查询,而不是将它们应用于 WHOLE查询(我知道这是因为我可以看到由Hibernate启动的本机SQL查询).

Because it is applying the ORDER BY to the first SQL query and then the same ORDER BY to the second SQL query, instead of apply them to the WHOLE query (I know this because I can see the native SQL queries launched by Hibernate).

这显然是Hibernate的不当行为.

This is clearly a missbehaviour of Hibernate.

如何解决此问题,以强制Hibernate将ORDER BY应用于整个查询? (我无法在内存中执行此操作,因为稍后我还必须添加分页功能.)

How can I work around this to force Hibernate to apply the ORDER BY to the whole query? (I cannot do it in memory because later I will have to add pagination also).

推荐答案

如果您使用以下内容,Hibernate将为您完成此操作.

Hibernate will do this for you if you use the following.

@Entity
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public abstract class AbstractEntity implements MyInterface {
    private int someField;
}

然后让您的子类执行此操作

Then have your subclasses that do this

@Entity
@Table(name="entity_1")
public class EntityOne extends AbstractEntity {
    private int someOtherField;
}

@Entity
@Table(name="entity_2")
public class EntityTwo extends AbstractEntity {
    private int anotherSomeOtherField;
}

然后,您应该能够像这样编写查询,以便与执行排序的数据库一起获得单个联合SQL查询.

You should then be able to write a query like this to get a single union SQL query with the DB doing the ordering.

FROM AbstractEntity ORDER BY someField

这篇关于如何解决此休眠限制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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