Ce contenu n'est pas disponible dans la langue sélectionnée.
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 Copier lienLien copié sur presse-papiers!
Copier lienLien copié sur presse-papiers!
First we need create our basic processing servlet. Since our servlet only handles HTTP
GET requests, we will only implement the doGet() method:
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.