1 Reply Latest reply on Mar 4, 2009 1:11 AM by Tim Evers

    Correct way to load lazy collections in Seam

    jk;l jkl; Expert

      If you set a collection on an entity to FetchType.LAZY because most of the time you don't need it, what's the correct way to load it in cases where you do need it?


      If you're using it on a given page, would you load the collection in the method pointed to in pages.xml for that page element's 'action' attribute? Or should you do it in the action method itself for that business action?


      What's the correct way to load the lazy collection? I'd been iterating over the entire collection and accessing some random property of the objects in the collection - ridiculously ugly code, especially if you do this at some point for every lazy collection in your entire system! What's the proper way to do this? (I could use the HQL fetch join but couldn't I do this at the object level without writing HQL?)


      Thanks.

        • 1. Re: Correct way to load lazy collections in Seam
          Tim Evers Master

          I don't really think that there is a 'correct' way of doing this.


          But there are a number of options available and some are better then others when it comes to code maintainability etc.


          My personal preference is that wherever you have your logic of looking up the entity, this is also where you load your collection. Either with HQL or Criteria.
          It's very unlikely that you could develop an application bigger then a petshop app without writing some queries to fetch the appropriate object graph for you.
          Letting SEAM's extended persistence context with Hibernate do all the work for you is not a good idea as you will end up executing much much more SQL then you should.


          Regardless of whether you are writing a SEAM(web) app or a Swing app you should always follow the principle of specifically loading the data you need for the page when you go to it. Not allowing some background/lazy initialization process to happen. If you let lazy initialization happen it abstract you away from what is actually going on in your application.


          However, if you don't want to write queries etc then don't forget about hibernate's helper for initializing collections.


          Hibernate.initialize(Entity.collection)