欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SSH整合中 hibernate托管给Spring得到SessionFactory

程序员文章站 2024-02-17 20:47:40
thread 然后 resou...
<prop key="hibernate.current_session_context_class">thread</prop>
然后
resource resource=new classpathresource("/web-inf/applicationcontext.xml");
beanfactory factory=new xmlbeanfactory(resource);
sessionfactory sessionfactory = (sessionfactory)factory.getbean("sessionfactory");
就可以得到了
剩下的 不会就回炉吧,我 的 做法是 修改hibernateutil文件的得到sessionfactory 的方法就 什么都解决了
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;
//在hibernate托管给spring时得到sessionfactory
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();
}
}
//
当hibernate没有托管给spring使用这种和传统方式都可以得到啊
sessionfactory = new configuration().configure("/web-inf/hibernate.cfg.xml")
.buildsessionfactory();