session在每个线程中只能有一个,那么我们可以通过ThreadLocal(Session)的方式来让session绑定到一个线程中,当然我们既然用框架那肯定还是选择配置来的快了,在配置文件中第二部分添加如下:
<property name="hibernate.current_session_context_class">thread</property>
然后就可以调用sessionFactory.getCurrentSession()了。
这种方式的session,hibernate会在事务commit() 或 rollback()的时候给我们自动关闭,无需我们手动关闭。