I have the problem that with Hibernate 5.1.17 + PostgreSQL JDBC driver 42.2.5, Hibernate seems to mix up the order of joins. The right order is important for performance.
The code:
import org.hibernate.Criteria
...
Criteria crit = session.createCriteria(EMSDataSet.class);
crit.createAlias("recordInformation", "recInf", JoinType.LEFT_OUTER_JOIN);
crit.createAlias("agencyInformation", "agencyInf", JoinType.LEFT_OUTER_JOIN);
... (lots of Joins)
crit.add(SQLTools.getDependedDateCriterion("recInf.created", getFrom(), getTo()));
ProjectionList proList = getQueryResultProjection(crit);
crit.setProjection(proList);
crit.setResultTransformer(Transformers.aliasToBean(QueryResult.class));
List result = crit.list();
jields to the query
select this_.db_id as y0_, this_.protocolStatus as y1_, recinf1_.created as y2_, recinf1_.id as y3_, (lots of other columns)
from EMSDataSet this_
left outer join AgencyInformationType agencyinf2_ on
this_.agencyInformation_db_id=agencyinf2_.db_id
... (lots of other joins)
left outer join RecordInformationType recinf1_ on this_.recordInformation_db_id=recinf1_.db_id
... (lots of other joins)
where (recinf1_.created>='2024-04-04' and recinf1_.created<'2024-04-14')
order by recinf1_.created desc, this_.db_id desc limit 100;
which is very slow (because it joins about 10 tables before the filter applies) - 3 seconds
In this case, the following query is indented:
select this_.db_id as y0_, this_.protocolStatus as y1_, recinf1_.created as y2_, recinf1_.id as y3_, (lots of other columns)
from EMSDataSet this_
left outer join RecordInformationType recinf1_ on this_.recordInformation_db_id=recinf1_.db_id
left outer join AgencyInformationType agencyinf2_ on this_.agencyInformation_db_id=agencyinf2_.db_id
... (lots of other joins)
where (recinf1_.created>='2024-04-04' and recinf1_.created<'2024-04-14')
order by recinf1_.created desc, this_.db_id desc limit 100;
In this case, PostgreSQL joins RecordInformationType at first, then filter, then joins the rest, which is much faster (200 ms).
Both results were verified with explain analyze
from PostgreSQL.
Now the question: How can I ensure the order?