Hibernate——openSession和getCurrentSession区别

openSession和getCurrentSession区别:

深入讨论:
在SessionFactory启动的时候,Hibernate会根据配置创建相应的CurrentSessionContext
在getCurrentSession()被调用的时候,实际上执行的方法是:CurrentSessionContext.currentSession()
在currentSession()执行时,如果当前Session为空,currentSession会调用SessionFactory的openSession


++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
* private static SessionFactory sessionFactory = null;
* /*使用线程局部模式*/
* private static ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
* static{
* sessionFactory = new Configuration().configure().buildSessionFactory();
* }
* /**
* * 获取和线程关联的session
* * @return
* */
* public static Session getCurrentSession(){
* Session session = threadLocal.get();
* /*判断是否得到*/
* if(session==null || !session.isOpen()){
* session = sessionFactory.openSession();
* //把session对象设置到threadLocal,相当于该session和线程绑定
* threadLocal.set(session);
* }
* return session;
* }
* /**
* * 获取全新的session
* * @return
* */
* public static Session openSession(){
* return sessionFactory.openSession();
* }
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

你可能感兴趣的:(Hibernate)