Managed web hosting - CHAPTER 16 Creating and testing layered applications this
CHAPTER 16 Creating and testing layered applications this point. You can not load uninitialized proxies and collections of an entity instance that is in detached state. If the Hibernate Session and therefore the persistence context is always closed at the end of the action s execute() method, Hibernate throws a LazyInitializationException when this unloaded association (or collection) is accessed. The persistence context is no longer available, so Hibernate can t load the lazy collection on access. FAQ Why can t Hibernate open a new Session if it has to lazy load objects? The Hibernate Session is the persistence context, the scope of object identity. Hibernate guarantees that there is at most one in-memory representation of a particular database row, in one persistence context. Opening a Session on-demand, behind the scenes, would also create a new persistence context, and all objects loaded in this identity scope would potentially conflict with objects loaded in the original persistence context. You can t load data on-demand when an object is out of the guaranteed scope of object identity when it s detached. On the other hand, you can load data as long as the objects are in persistent state, managed by a Session, even when the original transaction has been committed. In such a scenario, you have to enable the autocommit mode, as discussed in chapter 10, section 10.3, Nontransactional data access. We recommend that you don t use the autocommit mode in a web application; it s much easier to extend the original Session and transaction to span the whole request. In systems where you can t easily begin and end a transaction when objects have to be loaded on-demand inside a Session, such as Swing desktop applications that use Hibernate, the autocommit mode is useful. A first solution would be to ensure that all needed associations and collections are fully initialized before forwarding to the view (we discuss this later), but a more convenient approach in a two-tiered architecture with a colocated presentation and persistence layer is to leave the persistence context open until the view is completely rendered. The OSIV pattern allows you to have a single Hibernate persistence context per request, spanning the rendering of the view and potentially multiple action execute()s. It can also be implemented easily for example, with a servlet filter: public class HibernateSessionRequestFilter implements Filter { private SessionFactory sf; private static Log log = …; public void doFilter(ServletRequest request,
In case you need quality webspace to host and run your web applications, try our personal web hosting services.