    View Javadoc
    1   /*
    2    * Copyright (c) 2003
    3    * Information Desire GmbH
    4    * All rights reserved.
    5    */
    6   package com.infodesire.infobit.hibernate;
    7
    8   import net.sf.hibernate.Session;
    9   import net.sf.hibernate.Transaction;
    10  import net.sf.hibernate.SessionFactory;
    11  import net.sf.hibernate.HibernateException;
    12  /***
    13   * thread local session provider.
    14   *
    15   * @author    konstantin
    16   * @created   August 21, 2003
    17   * @version   $Revision: 1.4 $
    18   */
    19  public class ThreadLocalSessionProvider extends BaseSessionProvider {
    20
    21      ThreadLocal     _session = new ThreadLocal();
    22      ThreadLocal     _transaction = new ThreadLocal();
    23
    24
    25      /***
    26       * Gets the Session attribute of the DefaultSessionProvider object
    27       *
    28       * @return                        The Session value
    29       * @exception HibernateException  Description of Exception
    30       */
    31      public Session getSession() throws HibernateException {
    32          Session sess = (Session) _session.get();
    33          if (sess == null) {
    34              sess = getFactory().openSession();
    35              Transaction tr = sess.beginTransaction();
    36              _session.set(sess);
    37              _transaction.set(tr);
    38          }
    39          return sess;
    40      }
    41
    42
    43      /***
    44       * rollback current transaction. shall be called in cse of any hibernate
    45       * exception
    46       *
    47       * @exception HibernateException  Description of Exception
    48       */
    49      public void rollback() throws HibernateException {
    50          Transaction tr = (Transaction) _transaction.get();
    51          if (tr != null) {
    52              tr.rollback();
    53          }
    54          _transaction.set(null);
    55      }
    56
    57
    58      /***
    59       * give session back. without closing. no op here.
    60       *
    61       * @param sess  session to be returned
    62       */
    63      public void returnSession(Session sess) {
    64      }
    65
    66
    67      /***
    68       * give session back and close it
    69       *
    70       * @param sess                    session to be closed
    71       * @exception HibernateException  may be thrown by hibernate
    72       */
    73      public void returnCloseSession(Session sess) throws HibernateException {
    74          Transaction tr = (Transaction) _transaction.get();
    75          if (tr != null && !tr.wasCommitted() && !tr.wasRolledBack()) {
    76              tr.commit();
    77              _transaction.set(null);
    78          }
    79          sess.close();
    80          _session.set(null);
    81      }
    82  }
    83

This page was automatically generated by Maven