title: Hibernate session and transaction across methods
body: <p>I have a hibernate session that retrieved from <code>sessionFactory.openSession()</code>, And some complex computing to the <code>Entities</code> and also I want to persistent(<code>UPDATE, INSERT, DELETE</code>) some <code>Entities</code> during the computing. </p>
  
  <p>Here is a case:</p>
  
  <p>Consider that I have a <code>ProductEntity</code> that represents a product, and an <code>OrderEntity</code> which  represents the order record of the product, and a <code>UserEntity</code> which represents the user who book the order of the product.</p>
  
  <p>I know I can process an booking operation this way:</p>
  
  <pre><code>  public void addOrder(UserEntity userEntity, ProductEntity productEntity, int quantity){
         session = sf.openSession();
         Transaction tx = session.beginTransaction();
         //do some compution and generate the orderEntity and persistent it to the db.
         try{
            tx.commit();
         }catch(Exception e){
            tx.rollback();
         }finnaly{
            session.close();
         }
   }
  </code></pre>
  
  <p>Now I have to add more action to the procedure, such as (<em>Maybe</em>) making a <code>NotifyEntity</code> and stored in db which represents the notify records to the Merchant who owns the product. this <code>notify</code> record could be generated by the <code>orderEntity</code> and has nothing to do with the <code>productEntity</code> or <code>UserEntity</code>, in fact, I want this <code>notifyMerchantByOrderEntity</code> method separated-out of the <code>addOrder</code> procedure so that I can reuse this method and clarify the code( I really don't want to mess-up with a bulk of codes in the same method, in fact if the checking logic is complex enough, the code of the <code>addOrder</code> method could be very-very loooong).</p>
  
  <p>Anyhow, I want to :</p>
  
  <ul>
  <li>Separating a very long transaction to several methods</li>
  <li>But these methods should be considered together as a whole transaction(ie, they should rollback together when Exception occurs)</li>
  </ul>
  
  <p>Something like this:</p>
  
  <pre><code> public void addOrder(UserEntity userEntity, ProductEntity productEntity, int quantity){
      Session session = sf.openSession();
      session.beginTransaction();
      invokeOtherMethod();  //invoking other method which also contains some db operation.
      try{
         tx.commit()
      }catch(Exception e){
         tx.rollback(); //this should rollback the operation in invokeOtherMethod() too.
      }finally{
         session.close();
      }
   }
  </code></pre>