用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;
}
非常感谢作者!