hibernate, to be lazy or not to be lazy? [closed]

混江龙づ霸主 提交于 2019-12-03 16:12:30

For general considerations take a look at the Hibernate 3.6 docs about fetching strategies. The default fetching strategy is defined in mapping annotations or in a hbm.xml file. There are three ways to dynamically switch from a default lazy-loading strategy to an eager-loading strategy. The first two require separate implementations of DAO methods for lazy-loading and eager-loading use cases:

  1. Criteria.setFetchMode() in a Hibernate Criteria query
  2. FETCH keyword in a HQL query
  3. Since Hibernate 3.5 (not quite sure now, maybe 3.6) there is the third option of using fetch profiles to dynamically switch from lazy-loading to eager-loading.

A fetch profile is enabled/disabled on a session scope. So, provided the desired fetch profile is set in the current session, you can use the same DAO method for a lazy-loading as well as for an eager-loading use case.

The important thing to be aware of here is that you can only switch from a lazy-loading strategy defined in annotations or in a hbm.xml file to an eager-loading strategy and not vice versa. This restriction is independent of the method used for switching the fetching strategy.

Well, you described the problem correctly. It's just a tradeoff between simplicity (just one method) and performance (two methods, each returning exactly what is needed). If the response time is correct by just using the single method and lazy-loading the Bs, then don't touch anything. If the response time is too long, and you have measured that eager-loading it would make it correct, then introduce a new method.

Keep things simple, and optimize only if needed. Lazy-loading associations is fast, because it just make a query on a foreign key, whcih should be indexed in the database.

Also not that loading two toMany associations is pretty rare: it's common to show all the products of a category on a page, but it's uncommon to show all the puchases of all the products of a category.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!