How do you programmatically turn off eager fetching with hibernate?
Asked Answered
V

2

7

I have in my mapping an association to an eagerly loaded collection (lazy="false" fetch="subselect"). How can I turn that off programmatically with Hibernate when I do a query?

Vicar answered 3/9, 2009 at 10:46 Comment(0)
S
9

In fact, it is supposed to be the other way around. You turn it off in the mapping, and activate it on specific use cases with a "fetch" in the query.

That's the way the Hibernate team sees it. There is no way in Hibernate to create a request that specifies "no-fetch" for a property...

Skyler answered 3/9, 2009 at 10:52 Comment(2)
That's what I thought as well. I was just trying my luck if there's such a way to do it. ThanksVicar
You're very welcome. Is there something else that you need to consider your question as answered? I mean to accept the answer.Skyler
C
0

I had a situation that for historical reasons did eager fetch between several one-to-many dependencies. Over years many places came to depend on it so it was hard to turn off. However for some cases, the eager fetch was hindering: for every larger selection on the table, it would spawn 100s of small subqueries for each of the collections of each of the objects. I found a way to get around this, not really overriding the eager fetch, but for me just as useful: simply create a single query that does all the subfetches at once. This will make 1 physical query to the database, instead of having hibernate walk the dependency graph and spawn 100s of queries.

So I replaced

Query q = session.createQuery("from Customer c");

by

Query q = session.createQuery("from Customer c " +
            "left join fetch c.vats v " +
            "left join fetch v.klMemos bk " +
            "left join fetch bk.ferryKlMemos");

1 Customer has many VAT numbers, 1 VAT number has many klmemos and so on. The old situation would first fetch only the customers and hibernate would then start fetching each of the dependent collections one by one. The second form will load everything in one native query, and hibernate will find all it needs to populate the eager collections in the object cache. Hope it helps somebody. Note: I still think you should try to avoid eager fetches ;-)

Christabella answered 25/4, 2013 at 7:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.