<Prop key = "hibernate. current_session_context_class"> thread </prop>
Then
Resource resource = new ClassPathResource ("/WEB-INF/applicationContext. xml ");
BeanFactory factory = new XmlBeanFactory (resource );
SessionFactory sessionFactory = (SessionFactory) factory. getBean ("sessionFactory ");
You can get it.
The rest will not go back to the furnace. My approach is to modify the HibernateUtil file and get the SessionFactory method.
Import org. hibernate. HibernateException;
Import org. hibernate. Session;
Import org. hibernate. SessionFactory;
Import org. hibernate. cfg. Configuration;
Import org. springframework. beans. factory. BeanFactory;
Import org. springframework. beans. factory. xml. XmlBeanFactory;
Import org. springframework. core. io. ClassPathResource;
Import org. springframework. core. io. Resource;
// Get sessionFactory when hibernate is hosted on Spring
Public class HibernateUtil {
Private static final SessionFactory sessionFactory;
Static {
Try {
Resource resource = new ClassPathResource ("/WEB-INF/applicationContext. xml ");
BeanFactory factory = new XmlBeanFactory (resource );
SessionFactory = (SessionFactory) factory. getBean ("sessionFactory ");
} Catch (HibernateException ex ){
Throw new RuntimeException ("Exception building SessionFactory :"
+ Ex. getMessage (), 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 ();
}
}
//
This and traditional methods can be used when hibernate is not hosted on Spring.
SessionFactory = new Configuration (). configure ("/WEB-INF/hibernate. cfg. xml ")
. BuildSessionFactory ();