'Hibernate left join fetch by non-primary keys
Following entities:
@Table
class AA1 {
@Id
Long id;
String a_number;
Category category;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name= 'a_number', referencedColumnName='a_number')
@JoinColumn(name= 'category', referencedColumnName='category')
BB1 bb1
...other fields...
}
@Table
class BB1 {
@Id
String a_number;
Category category;
String value;
}
JPQL query:
SELECT a FROM AA1 a LEFT JOIN a.bb1 b;
Hibernate produces correct sql query, but when it tries to collect data it makes additional call like:
SELECT b.a_number, b.category, b.value FROM BB1 b WHERE b.a_number = ? AND b.category = ?
I checked that query returns null. How can I avoid such database queries?
My investigation: As far as I see Hibernate creates key by(AA1.a_number and AA1.category) and tries to retrieve entity from context. And for specific row 'left join' query returns null values and Hibernate asks context by key and context returns null, it leads to call to database for it.
Solution 1:[1]
Just looking at the entity definition @ManyToOne(fetch = FetchType.LAZY) is the cause.
You are explicitly telling JPA to fetch BB1 only when it is needed/accessed.Hence when the first call to get the parent entity is made BB1 is not loaded.It is only when you are accessing the child that triggers JPA to fetch it.
If you change it to FetchType.EAGER , both the entities will be queried in a single call.
But be careful there are advantages/pit-falls with either approach. Read more abt it here : https://thorben-janssen.com/entity-mappings-introduction-jpa-fetchtypes/
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Rambler |
