このコンテンツは選択した言語では利用できません。
2.5.2. 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:
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.