I'm running into LazyLoading exceptions like the most people who try remoting with an ORM. In most cases switching to eager fetching solves the problem (Lazy Loading / Non atomic queries / Thread safety / n+1 problem ...). But eager fetching has also disadvantages if you are dealing with a really big object graph.
Loading the whole object graph isn't needed in the most use-cases. It feels bad to load more data then needed (or load them from the db and extract the needed subset).
So what alternative ways are there to solve this kind of problem (at runtime)?
I've seen:
I thought a lot about another way. Maybe generic projection white./black listning is a solution.
Idea (blacklist): Define an classname list with the boundaries for a fetching operation. If a property matches and it's lazy, remove the lazy (CGLIB) proxy and fill the value with null. Else, simple prevent from fetching (and leave value at null). So we can set clear boundaries in our DAOs.
Example: ProductDao.findByName("Soap",Boundaries.BLACKLIST,"Category, Discount")
the two last parameters can also been bound into a Boundaries object.
Idea (whitelist): Like blacklist, but you must declare properties with should be loaded in a whitelist.
What do you think about such a solution? (Possible problems, restrictions, advantages ...) How should I write this in java? Maybe via AOP to match DAO methods (because I'm able to modifiy cglib proxy behaviour there)?
You can get rid of all collections whatsoever and use NamedQueries
instead. We used this approach in one project (EJB + Swing), and it worked pretty well - thus you determine exact data to be fetched.
NamedQueries are normal queries, imagine them as PreparedStatement-s. The idea is not to create/retreive/update/delete single objects with queries. The idea is that you fetch your Collections with queries. For example, instead of mapping a @ManyToMany List, define a NamedQuery that fetches that list. Thus you can fetch the collection data separately, and only whenever you need it, not automatically.
Use a custom Proxy (using CGLIB) for transferred objects - whenever a collection is referenced (via its getter), attempt retreival, and catch any LazyInitializationException
and make a call to the server tier for the data requested.
Just as the previous one, but make proxies only of the collections, in the way Hibernate proxies them when lazy initialization is needed.
Also, take a look at the Value List Handler pattern - might be useful.
(You can also use hibernate.max_fetch_depth
(if using Hibernate) with a combination of the above, if it is suitable for your case.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With