Struts 2 Hibernate Integration With Sessions per Request
Combine Struts 2 with Hibernate by opening a session per request in an interceptor or filter, keeping lazy loading working in JSPs, and managing transactions.

Struts 2 does not ship a Hibernate integration. There is no official plugin, so a project that wants both has to decide where the SessionFactory lives, who opens and closes the Session, and where the transaction boundary is. Getting that wrong is the source of the two classic problems in such applications: LazyInitializationException in a JSP, and sessions that are never closed. This post wires Hibernate 6 or 7 into Struts 6 by hand, with a session per request, explains why the session must outlive the action, and covers the common faults. If the project also uses Spring, the better arrangement is in Struts 2 with Spring.
The SessionFactory is built once
A SessionFactory is expensive to build, since it reads the mappings, builds metadata and may validate the schema, and it is thread-safe. Create one per application, at startup, and reuse it. A servlet context listener is the simplest home:
@WebListener
public class HibernateListener implements ServletContextListener {
static SessionFactory factory;
@Override
public void contextInitialized(ServletContextEvent event) {
factory = new Configuration().configure().buildSessionFactory();
}
@Override
public void contextDestroyed(ServletContextEvent event) {
if (factory != null) factory.close();
}
}configure() reads hibernate.cfg.xml from the classpath, which holds the connection settings and the mapped classes. Closing the factory on shutdown releases the connection pool, and without it redeploys on Tomcat leak threads and memory. A static field is acceptable here because the factory is application-wide; wrap access in a small HibernateUtil class so the rest of the code does not touch the listener.
A request-scoped session
A Session is cheap and not thread-safe: one per request, never shared. Open it before the action runs and close it after the view has rendered. Struts interceptors wrap the action, so an interceptor is the natural place:
public class SessionInterceptor extends AbstractInterceptor {
@Override
public String intercept(ActionInvocation invocation) throws Exception {
Session session = HibernateListener.factory.openSession();
Transaction tx = session.beginTransaction();
ThreadSessions.bind(session);
try {
String result = invocation.invoke();
tx.commit();
return result;
} catch (Exception e) {
if (tx.isActive()) tx.rollback();
throw e;
} finally {
ThreadSessions.unbind();
session.close();
}
}
}ThreadSessions is a small helper that holds the session in a ThreadLocal, so DAO classes can find it without a parameter. Register the interceptor in struts.xml and add it to the stack your actions use:
<interceptors>
<interceptor name="hibernateSession" class="com.example.SessionInterceptor"/>
<interceptor-stack name="appStack">
<interceptor-ref name="hibernateSession"/>
<interceptor-ref name="defaultStack"/>
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="appStack"/>Order matters. The session interceptor goes first, so everything after it runs inside the transaction, including parameter binding and validation if they touch the database. Interceptors are described in the Struts interceptors documentation.
Be aware of what invocation.invoke() includes. It runs the action and the result, which renders the JSP, in the default configuration. The commit therefore happens after the page is generated. That is deliberate and has a consequence discussed next, and a cost: a slow template holds the database connection.
Why the view must run inside the session
A JSP reading ${order.lines} for a lazily loaded collection needs an open session at that moment, or Hibernate throws LazyInitializationException. Keeping the session open until the view renders is the pattern called open session in view. It makes the JSP code simple, and it hides two kinds of problem.
It hides N+1 queries. A loop in the page that touches a lazy association per row fires one query per row, from the view, where nobody looks. If a page is slow, enable SQL logging and count the statements, as in the N+1 problem. Fetch what the page needs in the action with a join fetch or an entity graph.
It lets the view change the database. A getter that triggers a write, or an entity modified in the template, is flushed at commit. Keep entities read-only in views, or copy data into simple objects in the action and render those.
The alternative, closing the session before the view and fetching everything in the action, is cleaner and less convenient. Move the commit into a separate interceptor placed before the result, or use data transfer objects. Choose one and apply it everywhere; a mix confuses everyone who works on the project afterwards.
The action
public class OrderAction extends ActionSupport {
private Long id;
private Order order;
@Override
public String execute() {
Session session = ThreadSessions.current();
order = session.createQuery(
"select o from Order o join fetch o.lines where o.id = :id", Order.class)
.setParameter("id", id)
.getSingleResult();
return SUCCESS;
}
public void setId(Long id) { this.id = id; }
public Order getOrder() { return order; }
}The query fetches the lines in the same statement, so the page does not depend on session-in-view. Use getSingleResult only where the row must exist, and handle NoResultException into a "not found" result, not a stack trace.
Testing the data layer apart from Struts
The interceptor is the only place that knows about Struts, so everything below it can be checked without a web container. Write DAO tests that open a session from a test SessionFactory backed by an in-memory or Testcontainers database, bind it with the same ThreadSessions helper, and roll back at the end of each test. For the action, a StrutsSpringTestCase-style harness is heavy; call execute() directly on a new action object with a session bound, and assert on the fields the JSP would read. The interceptor itself needs two tests: one that a thrown exception rolls back and one that the session is closed on every path, using a spy Session.
Transaction boundaries beyond one action
A request that needs two units of work with a commit in between, such as saving an order and then sending an email whose failure must not undo the order, does not fit a single transaction per request. Commit explicitly inside the action, start a new transaction afterwards, and keep the interceptor's commit as the default for the simple case. Document the exception in the action. Silent partial commits are the hardest bugs to reproduce in this kind of setup, because the interceptor cannot tell that an earlier commit already happened.
Connection pool size should follow the number of concurrent requests that hold a session. With open session in view, a connection is held for the whole request, including template rendering and any slow call to another service made from the action, so a pool of ten serves ten slow requests at a time. Release the session earlier for pages that call external services, or call them before the session opens.
Common problems
LazyInitializationException means the session closed before the view, or the entity was kept in the HTTP session across requests, where it is detached. Do not store entities in the HTTP session; store ids. StaleObjectStateException appears when two users edit the same row and you use a version column, and the handling is in locking failures. Connections run out when an exception skips the finally, so check that every path closes the session. A transaction that never commits shows up as data that is not saved, because the interceptor swallowed an exception, so log inside the catch.
Where this does not apply
If you already use Spring, let it manage the session and use @Transactional services, which replaces the interceptor. If you plan to leave Struts, keep the persistence layer free of Struts types so it moves with you, see migrating Struts to Spring MVC. The session handling API is documented in the Hibernate user guide.


