title: Hibernate Open Session in View: Transaction per Request?
body: <p>I'm using Hibernate with Spring on Tomcat.  I've been reading and re-reading the oft pointed to <a href="https://community.jboss.org/wiki/OpenSessioninView" rel="noreferrer">JBoss wiki page</a> on the topic, and that has been helpful.  But it leaves me with some questions.</p>
  
  <ol>
  <li><p>The idea of starting a transaction for every request troubles me.  I guess I could limit the filter to certain controllers -- maybe put all my controllers that need a transaction under a pseudo "tx" path or something.  But isn't it a bad idea to use transactions if you don't know if you're going to need one?  And if I'm just doing reads in some request -- reads that very likely may come from a cache -- aren't I better off without a transaction?</p></li>
  <li><p>I've read posts mentioning how they handled the transactions at the service layer, and I'd like to do this with Spring.  But then what does the filter code look like?  I still want the session available in my view for some lazy loading.</p></li>
  <li><p>If all I have to do is call <code>sessionFactory.getCurrentSession()</code> in my filter, how does it get "freed" back to the session factory for re-use?  (I expected to see a <code>session.close()</code> or something, even when using transactions.)  Who is telling the session factory that that session can be reused?</p></li>
  <li><p>Perhaps it's the <code>beginTransaction()</code> call that binds a given database connection to a given session for the duration of a request?  Otherwise, a session pulls db connections from the pool as needed, right?</p></li>
  </ol>
  
  <p>Thanks for your patience with all my questions.</p>
  
  <p>(And if your answer is going to be a link to the Spring documentation, you'll just make me cry.  You don't want that, do you?  I'll pay real money if people would stop answering Spring-related questions that way.)</p>