How to overcome the performance issues caused by the generated SQL of union-subclass in Hibernate

StackOverflow https://stackoverflow.com/questions/10572408

  •  08-06-2021
  •  | 
  •  

Question

I am using Hibernate support for TABLE_PER_CLASS inheritance strategy. Functionality wise it works well. Whenever polymorphic query is issued Hibernate generates an SQL containing "union all" for my two concrete classes A & B. The generated SQL has the following format:

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

The problem this approach suffers from really bad performance on the DB side. Taking into account C1 column is a shared property of ClassA and ClassB (derived from abstract parent) Hibernate could insert the where clause in both sub selects and dramatically improve performance. For example,

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

Some optimization could also be done on the limit. I am using Hibernate criteria API in my DAO layer.

Interceptor, onPrepareStatment() could not be used since arguments are not visible. Using partitions and possibly other options on the DB is currently out of the scope as we want to avoid DB specific optimization at this phase of the work.

Any idea how to manipulate hibernate to improve performance?

No correct solution

OTHER TIPS

I you want high cross-database performance than I'd recommend not using table-pr-class and many or huge polymorphic queries. A discriminator column would usually be better.

Note that you can combine table-pr-class with discrimantor-columns if you have more than two levels in your class hierchy.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top