1.4. 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. We 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.4.1. Writing the basic servlet

Create a new class in your source directory, in the events package:
package events;

// Imports

public class EventManagerServlet extends HttpServlet {

    // Servlet code
The servlet handles HTTP GET requests only, hence, the method we implement is doGet():
protected void doGet(HttpServletRequest request,
                     HttpServletResponse response)
        throws ServletException, IOException {

    SimpleDateFormat dateFormatter = new SimpleDateFormat("dd.MM.yyyy");

    try {
        // Begin unit of work

        // Process request and render page...

        // End unit of work

    } catch (Exception ex) {
        throw new ServletException(ex);

The pattern we are applying 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. Then a database transaction is started - all data access as to occur inside a transaction, no matter if data is read or written (we don't 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'll get to that part soon.
Finally, the unit of work ends when processing and rendering is complete. If any problem occured 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'll need it as soon as you consider rendering your view in JSP, not in a servlet.