10.4. Integrating Struts with Hibernate

Problem

You want to use Hibernate for object/relational mapping in your Struts application.

Solution

Use a servlet filter such as the Persistence class shown in Example 10-11.

Example 10-11. Servlet filter for Hibernate sessions

package com.jadecove.util; import java.io.*; import javax.servlet.*; import net.sf.hibernate.*; import net.sf.hibernate.cfg.Configuration; /** * Filter which manages a ThreadLocal hibernate session. Obtain the session * by calling Persistance.getSession( ). */ public class Persistence implements Filter { /** * Holds the current hibernate session, if one has been created. */ protected static ThreadLocal hibernateHolder = new ThreadLocal( ); protected static SessionFactory factory; public void init(FilterConfig filterConfig) throws ServletException { // Initialize hibernate try { doInit( ); } catch (HibernateException ex) { throw new ServletException(ex); } } /** * This method should only be called when this class is used directly - * that is, when using this class outside of the servlet container. * @throws HibernateException */ public static void doInit( ) throws HibernateException { factory = new Configuration( ).configure( ).buildSessionFactory( ); } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (hibernateHolder.get( ) != null) throw new IllegalStateException( "A session is already associated with this thread! " + "Someone must have ...

Get Jakarta Struts Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.