Reputation: 5867
I have a criteria query to retrieve parent and all its children. But hibernate is firing multiple queries to fetch children. I have used default InnerJoin fetch while creating criteria, and also tried setting fetchMode.Join. But nothing works.
So, what is the difference between FetchMode.Join and JoinType. I thought Jointype alone is sufficient to fetch data from both the tables in a single query. But is this the case?
Secondly, when criteria query will fire multiple queries to fetch childrens.?
Upvotes: 0
Views: 1332
Reputation: 5064
@Fetch(FetchMode.JOIN)
says that related entities will be retrieved using join SQL query, but it also breaks laziness, it means even if you mark your child entity as fetch = FetchType.LAZY
it won't work. In order to prevent the secondary query use join fetch
- Using the JPA Criteria API, can you do a fetch join that results in only one join?
and I don't recommend to use @Fetch
at all.
Follow up to read: Java Persistence with Hibernate. 2nd edition
- 15.4.5 Dynamic fetching with joins
:
Queries ignore any fetching strategy you’ve defined in mapping metadata with @org.hibernate.annotations.Fetch. For example, mapping the bids collection with org.hibernate.annotations.FetchMode.JOIN has no effect on the queries you write. The dynamic fetching strategy of your query ignores the global fetching strategy. On the other hand, Hibernate doesn’t ignore the mapped fetch plan: Hibernate always considers a FetchType.EAGER, and you may see several additional SQL statements when you execute your query.
Just so you know - EAGER
does not work for queries - https://vladmihalcea.com/eager-fetching-is-a-code-smell/
It almost always generates additional queries, so, that's the answer for you question - when criteria query will fire multiple queries to fetch childrens?
Upvotes: 2