如何克服Hibernate中生成的union-subclass SQL引起的性能问题

时间:2012-05-13 14:08:44

标签: hibernate jpa union-subclass

我正在使用Hibernate支持TABLE_PER_CLASS继承策略。功能明智,它运作良好。每当发出多态查询时,Hibernate都会为我的两个具体类A和A生成一个包含“union all”的SQL。 B.生成的SQL具有以下格式:

select C1, C2, C3 from (
    select C1, C2, C3 from ClassA
  union all
    select C1, C2, C3 from ClassB
)
where 
    C1 == <value>
order by C2
limit 100

这种方法的问题在数据库端的性能非常糟糕。考虑到C1列是ClassA和ClassB的共享属性(从抽象父类派生)Hibernate可以在两个子选择中插入where子句并显着提高性能。例如,

select C1, C2, C3 from ( 
    select C1, C2, C3 from ClassA where C1 == <value>
    union all
    select C1, C2, C3 from ClassB where C1 == <value>
)
order by C2
limit 100

也可以在限制上进行一些优化。 我在DAO层使用Hibernate标准API。

由于参数不可见,因此无法使用Interceptor,onPrepareStatment()。 在数据库中使用分区和可能的其他选项目前已超出范围,因为我们希望在此阶段工作中避免使用特定于数据库的优化。

知道如何操作hibernate以提高性能吗?

1 个答案:

答案 0 :(得分:0)

我想要高跨数据库性能而不是我建议不使用table-pr-class和许多或大量的多态查询。鉴别器列通常会更好。

请注意,如果您的类中有两个以上的级别,则可以将table-pr-class与discrimantor-columns组合使用。