javahibernatemaveneclipse-pluginhbm2java

Getting SEVERE: Could not locate SessionFactory in JNDI while getting sessionfactory


I am using hibernate as persistence layer to communicate with the database. I used maven plugin hbm2java to generate dao, java, *hbm.xml and hibernate.cfg.xml. till that time plugins works fine.

But when I trying to communicate to db it gives following exception.

Aug 30, 2012 1:45:46 PM org.hbm2dao.AssemblyHome getSessionFactory
SEVERE: 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(Unknown Source)
at javax.naming.InitialContext.getDefaultInitCtx(Unknown Source)
at javax.naming.InitialContext.getURLOrDefaultInitCtx(Unknown Source)
at javax.naming.InitialContext.lookup(Unknown Source)
at org.hbm2dao.AssemblyHome.getSessionFactory(AssemblyHome.java:29)
at org.hbm2dao.AssemblyHome.<init>(AssemblyHome.java:24)
at com.myhadoop.app.App.main(App.java:22)
java.lang.IllegalStateException: Could not locate SessionFactory in JNDI
at org.hbm2dao.AssemblyHome.getSessionFactory(AssemblyHome.java:33)
at org.hbm2dao.AssemblyHome.<init>(AssemblyHome.java:24)
at com.myhadoop.app.App.main(App.java:22)
Exception in thread "main" java.lang.NullPointerException
at com.myhadoop.app.App.main(App.java:32)

by default hibernate3:hbm2cfgxml generates hibernate.cfg.xml file with session-factory name as SessionFactory. just like following.

<session-factory name="SessionFactory">

plugin generate following code to get session factory.

private final SessionFactory sessionFactory = getSessionFactory();

protected SessionFactory getSessionFactory() {
    try {

        return (SessionFactory) new InitialContext().lookup("SessionFactory");
    }
    catch (Exception e) {
        log.error("Could not locate SessionFactory in JNDI", e);
        throw new IllegalStateException("Could not locate SessionFactory in JNDI");
    }
}

I found similar query Problems using eclipse Hibernate plugin - could not locate sessionfactory in JNDI.

However it not feasible to change 400+ classes generated by plugin to get session factory from *Home.java.

How to get rid of this problem with the hibernate plugin without changing 400+ classes?

I do not want to use any web/app server this is my standalone application.


Solution

  • Using that generated getSessionFactory() method will only work if you have set up your environment such that InitialContext can find your hibernate.cfg.xml file, and it sounds like it can't.

    You can fix that problem by setting up InitialContext and your environment correctly as per the InitialContext javadocs. As an alternative, you can cut out JNDI entirely by changing the getSessionFactory method to simply create a Configuration, and telling it where the mapping file(s) are.