session-per-request
session-per-request DESIGN PATTERN:
1 package org.hibernate.tutorial.web; 2 3 // Imports 4 5 public class EventManagerServlet extends HttpServlet { 6 7 protected void doGet( 8 HttpServletRequest request, 9 HttpServletResponse response) throws ServletException, IOException { 10 11 SimpleDateFormat dateFormatter = new SimpleDateFormat( "dd.MM.yyyy" ); 12 13 try { 14 // Begin unit of work 15 HibernateUtil.getSessionFactory().getCurrentSession().beginTransaction(); 16 17 // Process request and render page... 18 19 // End unit of work 20 HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().commit(); 21 } 22 catch (Exception ex) { 23 HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().rollback(); 24 if ( ServletException.class.isInstance( ex ) ) { 25 throw ( ServletException ) ex; 26 } 27 else { 28 throw new ServletException( ex ); 29 } 30 } 31 } 32 33 }
When a request hits the servlet, a new HibernateSession 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.

浙公网安备 33010602011771号