Quite recently I had one interesting case related to the quality of code generated by the Hybernate, in which I developed code which runs 25 thousand times faster than the code generated by the framework.
It’s well known when you decide to use any framework to speed up code development process, you silently agree to lose a certain level of control.
Hybernate – a popular and mature Java JPA framework is not an exception.
Here is conceptual code generated by the Hybernate framework.
select col1, col2... from table1 join table2 ... where ...
And here is manually tuned code which appears to be 25K times faster than the code generated by the Hyvernate framework.
with tmp as (select col1 from table1 jin table2...where ...) select col1, col2... from table1 join table2 ... where col1 in (select col1 from tmp)
The main reason why I’ve got such a huge difference is because Hybernate is not capable to produce good enough code when facing with many entities/tables with complex relations among them, which is a curse of all frameworks.
In case you are not using Hybernate, you can just replace bad code with tuned one and you are done.
If you are using packed framework like Hybernate in this case, this is not possible without major rewriting of already developed code which will trigger the whole process of testing and delays in deliveries.
The best you can do is to try to replace Hybernate FetchType EAGER fetching with LAZY.
Imagine you have two entities called Departments (Parent) and Employees (Child).
EAGER fetching instructs Hybernate to always retrieve dependent associations (Employees in this case) whenever a root entity (in this case Department) gets loaded, even it is not needed.
LAZY means to load on demand what you need.
If you need only data from the Department entity, LAZY loading will load only Department fields, while EAGER will load both: Department and Employees.
This is an typical example of one of the fundamental tuning technique – to use only what you need.
However, in case you always need to load all entities, then the only way is not to use Hybernate, and to manually rewrite that piece of code.