1.3. Part 3 - The EventManager web application
A Hibernate web application uses
Session
and Transaction
almost like a standalone application. However, some common patterns are useful. You can now write an EventManagerServlet
. This servlet can list all events stored in the database, and it provides an HTML form to enter new events.
1.3.1. Writing the basic servlet
First we need create our basic processing servlet. Since our servlet only handles HTTP
GET
requests, we will only implement the doGet()
method:
package org.hibernate.tutorial.web; // Imports public class EventManagerServlet extends HttpServlet { protected void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { SimpleDateFormat dateFormatter = new SimpleDateFormat( "dd.MM.yyyy" ); try { // Begin unit of work HibernateUtil.getSessionFactory().getCurrentSession().beginTransaction(); // Process request and render page... // End unit of work HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().commit(); } catch (Exception ex) { HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().rollback(); if ( ServletException.class.isInstance( ex ) ) { throw ( ServletException ) ex; } else { throw new ServletException( ex ); } } } }
Save this servlet as
src/main/java/org/hibernate/tutorial/web/EventManagerServlet.java
The pattern applied here is called session-per-request. When a request hits the servlet, a new Hibernate
Session
is opened through the first call to getCurrentSession()
on the SessionFactory
. A database transaction is then started. All data access occurs inside a transaction irrespective of whether the data is read or written. Do not use the auto-commit mode in applications.
Do not use a new Hibernate
Session
for every database operation. Use one Hibernate Session
that is scoped to the whole request. Use getCurrentSession()
, so that it is automatically bound to the current Java thread.
Next, the possible actions of the request are processed and the response HTML is rendered. We will get to that part soon.
Finally, the unit of work ends when processing and rendering are complete. If any problems occurred during processing or rendering, an exception will be thrown and the database transaction rolled back. This completes the
session-per-request
pattern. Instead of the transaction demarcation code in every servlet, you could also write a servlet filter. See the Hibernate website and Wiki for more information about this pattern called Open Session in View. You will need it as soon as you consider rendering your view in JSP, not in a servlet.