How often have you run into the dreaded LazyInitializationException with Spring and Hibernate?
Originally posted by Mark Spritzler:
Also, just to point out, in Spring Webflow 2.x you can now have a persistence context in your flow definition, so that if you did have to implement Open Session in View, now you don't. But that I believe is a recent addition, so probably not many people know this.
Originally posted by Dan Allen:
Mark, as you point out, the new persistence context management in Spring WebFlow is one of the crowning features in version 2.0. It puts Spring WebFlow on par with Seam in its ability to prevent the LazyInitializationException. As I might have mentioned before, there is no special sauce that Seam is applying here. The persistence context just needs to be extended beyond the request, in certain cases, and Spring WebFlow offers a suitable vehicle for doing so.
It's true that if you understand Hibernate well, and understand why a LazyInitializationException is thrown, then you also know what to do to avoid bumping into it. Unfortunately, for those that are just starting with Hibernate, or do not have the inclination to learn how Hibernate works internally, this exception starts to cut into their productivity quite dramatically (to the point where they would be better off just writing the SQL). Thus, developers appreciate having this problem solved for them, whether it be by Seam or Spring WebFlow.
Regardless, the extended persistence context is not really about avoiding this exception. It is about recognizing that this exception indicates an improper use of the persistence context. You shouldn't necessarily have to collect up all the data you need before leaving the service layer (like a Chipmunk collecting nuts before winter sets in). Rather, you should keep that persistence context available while you are actively using the entities that it manages, not only to allow crossing lazy associations, but to get the dirty checking, identity guarantees, optimistic locking, and deferred flushing. This is a topic I go into tremendous detail about in chapters 8 and 9 of Seam in Action.