Hibernate session管理

SessionFactory负责创建Session,SessionFactory是线程安全的,多个并发线程可以同时访问一个SessionFactory 并从中获取Session 实例。而Session并非线程安全,也就是说,如果多个线程同时使用一个Session实例进行数据存取,则将会导致Session 数据存取逻辑混乱。

1  它使用了ThreadLocal类别来建立一个 Session管理的辅助类

这是Hibernate Session管理一个广为应用的解决方案,ThreadLocal是Thread- Specific Storage模式的一个运作实例

HibernateUtil.java   
import net.sf.hibernate.*;   
import net.sf.hibernate.cfg.*;   
public class HibernateUtil {   
private static Log log = LogFactory.getLog(HibernateUtil.class);   
private static final SessionFactory sessionFactory;   
static {   
try {   
// Create the SessionFactory   
sessionFactory = new Configuration().configure().buildSessionFactory();   
} catch (Throwable ex) {   
log.error("Initial SessionFactory creation failed.", ex);   
throw new ExceptionInInitializerError(ex);   
}   
}   
public static final ThreadLocal session = new ThreadLocal();   
public static Session currentSession() throws HibernateException {   
Session s = (Session) session.get();   
// Open a new Session, if this Thread has none yet   
if (s == null) {   
s = sessionFactory.openSession();   
session.set(s);   
}   
return s;   
}   
public static void closeSession() throws HibernateException {   
Session s = (Session) session.get();   
session.set(null);   
if (s != null)   
s.close();   
}   
}   
2   在Web应用程序中,我们可以藉助Filter来进行Session管理,在需要的时候开启Session,并在Request结束之后关闭Session

public class PersistenceFilter implements Filter {  
  protected static ThreadLocal hibernateHolder = new ThreadLocal();  
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {  
    hibernateHolder.set(getSession());  
    try {        
      chain.doFilter(request, response);        
    } finally {  
      Session session = (Session) hibernateHolder.get();  
      if (session != null) {  
        hibernateHolder.set(null);  
        try {  
          session.close();  
        } catch (HibernateException ex) {  
          throw new ServletException(ex);  
        }  
      }  
    }  
  }     
}  




你可能感兴趣的:(Hibernate,session,filter,null,Class,import)