HIbernate SQL show_sql uses lots of left joins vs individual queries

Viewed 22

We are upgrading a legacy application from using xml files to annotations with Hibernate 5 (5.6.9 - I'm not sure what the old version of Hibernate was). The new application is running much slower than the old. I logged the sql queries between the old and new and the old application would make more queries to single tables while the new application is making fewer queries with lots of left joins. From what I can tell the annotations for the relationships seem to be equivalent to the old xml settings.

Is there a way to control how Hibernate writes its sql statements?

2 Answers

The default fetch mode of ManyToOne associations is EAGER since Hibernate 5.2 (per JPA specification), in case you need a lazy fetch as it was the case prior to that, you can add the fetch type:

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "country_id")
public Country getCountry() {

The explanation for what we were seeing was the fetch mode (vs fetch type: eager vs lazy). It seems the default fetch mode of the old version of Hibernate was SELECT but the default for Eager joins in Hibernate 5 is JOIN. To change you can add a @FETCH annotation. This didn't fix all of our slowness issues but it explained the difference in generated sql.

@Fetch(FetchMode.SELECT)

Some helpful links

Related