您的位置:首页 > 编程语言 > Java开发

最近用STS搭建hibernate&spring,遇到Could not locate SessionFactory in JNDI.找到这个文章很快解决了

2012-11-10 10:36 507 查看
用HIBERNATE时出现如下错误:

ERROR - Could not locate SessionFactory in JNDI

javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial

at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:645)

at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:247)

at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.java:284)

at javax.naming.InitialContext.lookup(InitialContext.java:351)

at com.lmy.myblog.pojos.THostInfoHome.getSessionFactory(THostInfoHome.java:27)

at com.lmy.myblog.pojos.THostInfoHome.<init>(THostInfoHome.java:22)

at Test.main(Test.java:13)

Exception in thread "main" java.lang.IllegalStateException: Could not locate SessionFactory in JNDI

at com.lmy.myblog.pojos.THostInfoHome.getSessionFactory(THostInfoHome.java:30)

at com.lmy.myblog.pojos.THostInfoHome.<init>(THostInfoHome.java:22)

at Test.main(Test.java:13)

需要修改的两个地方:

protected SessionFactory getSessionFactory() {

try {

//return (SessionFactory) new InitialContext().lookup("SessionFactory");这句不能通过,会提示Could not locate SessionFactory in JNDIjavax.naming.NoInitialContextException:
Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial

修改为

return (SessionFactory) new Configuration().configure().buildSessionFactory();

}

catch (Exception e) {

log.error("Could not locate SessionFactory in JNDI", e);

throw new IllegalStateException("Could not locate SessionFactory in JNDI"+e.toString());

}

}

public Tb1 findById( java.lang.String id) {

log.debug("getting Tb1 instance with id: " + id);

try {

System.out.println("test0....."+sessionFactory);

//Tb1 instance= (Tb1)sessionFactory.getCurrentSession().get(“com.sss.common”,id);//这句有问题。会提示No CurrentSessionContext configured!

修改为如下两句

Session session = sessionFactory.openSession();//先加入import org.hibernate.Session;

//Tb1 instance = (Tb1) session.load("com.sss.commmon.Tb1", id);这句也可以

Tb1 instance = (Tb1) session.get("com.sss.commmon.Tb1", id);

if (instance==null) {

log.debug("get successful, no instance found");

}

else {

log.debug("get successful, instance found");

}

return instance;

}

catch (RuntimeException re) {

log.error("get failed", re);

throw re;

}

原网页链接http://gotosleep.blog.sohu.com/20756325.html

非常感谢作者!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐