SSH integration where hibernate is hosted to Spring gets SessionFactory

  • 2020-05-09 19:03:43
  • OfStack

< 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 get it
I'm not going to do the rest of it. What I'm going to do is I'm going to modify the HibernateUtil file and I'm going to get the SessionFactory file and I'm going to get everything, right
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 by 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();
}
}
//
When hibernate is not hosted for Spring it is available both in this and traditional way
sessionFactory = new Configuration().configure("/WEB-INF/hibernate.cfg.xml")
.buildSessionFactory();

Related articles: