Tuesday, September 6, 2011

How transparently can you implement open session in view late in development?

On the Recordings project, we set up hibernate to eagerly load everything. I'm not sure why we made that decision (it was 8 months ago) but we've been busy getting rid of that practice. When deciding how to handle the lazy loading problem, we found a few different solutions:

  1.  Create different presentation objects for different pages and eagerly load everything into those -- pages that only need certain properties would get a class only containing those properties. 
  2. Add flags to our data access methods that indicate what to fetch
  3. Keep the db connection open while the view is being rendered (known as the Open Session in View pattern)
Approach (1) seems like a sound approach (and we've done it before in other projects) but would add too much additional maintenance and work this late in the development, as we're trying to restrict ourself to bug fixes and performance enhancements as necessary.

Approach (2) really seems ugly because not only does the data layer get convoluted -- it exposes the idea of "lazy loading" to other layers that shouldn't care about it, since they now have to decide what items they need.

So we've taken approach #3. We've implemented it by using a servlet filter that runs before any servlets. It simply opens a new session and then closes the session after the request is completed. One drawback is that if anything goes wrong with the database, the code that's responsible isn't shown in the stack trace. Instead, it shows the servlet filter as the cause which is not helpful.

A good (though painful) thing is that it's forced us to consolidate all of our data access code into one class. We have more than one class in our data layer, but they all extend one class (called BasicHibernateDataSource) which handles acquiring the session object. Our db tests also failed after doing this until we set up a basic database test class that mimics the servlet filter.

Although it seems like a lot, I think the effort required to implement it has still been "less" effort than the other two approaches, or at least the most transparent. This has allowed us to avoid introducing many new bugs due to adding a bunch of different functionality a this stage -- we're trying to push on so we can get it live as soon as possible.

No comments:

Post a Comment