Suppose I have the following class:
public class Foo {
public Bar bar;
}
One giant iBATIS query loads many instances of Foo and populates all of the bar fields from a database. I would like to split up the giant query into two:
- One query to load many
Fooinstances, leaving thebarfields null. - Another query to load all of the
barfields for some associatedFooinstances.
The idea is that the first query would be executed initially, then the second would be executed only if needed later on.
The trick is the association. I can batch load bar fields, but what’s the best way to inject that data back into the associated Foos? Is there any way around having one query executed per lazily-loaded instance field? This seems like it would counteract the performance benefits of iBATIS.
Although it is tempting to load object graphs from the database, we usually try to avoid that because it means one query per member, and when fetching large sets, can result in many, many queries on the database and long response times.
Therefore we usually model it in such a way that the member is seperated. Let’s say you have a Shop with Users. Instead of modelling the Users as a list in your shop, you have a DAO call which reads “List getUsersForShop(shop)”.
Some of our pages go even furter. For paginated web pages, there’s no use to get all objects from the database, since they’re not displayed at the same time. So we split it even further:
List getUserIdsForShop(shop)
and then for each row on the page, we do “User getUserForId(long id)”.
This will result in minimal dataflow between the server, the database and the client, and will reduce the number of calls per page. If your search result is 10.000 users, but you only display 10 per page, you’ve just saved the fetching of 99990 users, and holding them in memory.
Don’t use this as a hammer for all your nails. It’s just an option to consider for large object graphs.