Page 1 of 2 12 LastLast
Results 1 to 10 of 14

Thread: Session factory is null

  1. #1
    Join Date
    Aug 2006
    Posts
    9

    Default Session factory is null

    Hello:

    I am new with Spring + Hibernate and I am having a problem with a DAO: session factory always is null and it is impossible to me to get data with de the DAO.

    I am using:
    - Oracle as database
    - JDevloper as IDE (with the OC4J embedded)
    - Spring 1.2.8
    - Hibernate 3.1

    This is my DAO class:
    package com.sqs.pruebas.model.dao.event;

    import java.util.Collection;
    import java.util.List;
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.springframework.dao.DataAccessException;
    import org.springframework.dao.DataRetrievalFailureExcept ion;
    import org.springframework.orm.hibernate3.SessionFactoryU tils;
    import org.springframework.orm.hibernate3.support.Hiberna teDaoSupport;

    public class EventoDAOImpl extends HibernateDaoSupport implements EventoDAO {

    private SessionFactory sessionFactory;

    public EventoDAOImpl() { }

    public Collection loadEventosById(String idEvento) throws DataAccessException {
    SessionFactory sesionFactory = getSessionFactory();
    // After the previous code line sesionFactory always is null and NullPointerException is thrown
    Session sesion = SessionFactoryUtils.getSession(sesionFactory, false);
    List result = sesion.createQuery("from Evento evento where evento.id=?").setParameter(0, idEvento).list();
    if (result == null) {
    throw new DataRetrievalFailureException("");
    }
    return result;
    }
    }



    This is my mapping file (generated with XDoclet):
    <?xml version="1.0" encoding="UTF-8"?>

    <!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

    <hibernate-mapping>
    <class
    name="com.sqs.pruebas.domain.event.Evento"
    table="EVENTOS">
    <id name="id"
    column="ID_EVENTO"
    type="java.lang.String">
    <generator class="native">
    </generator>
    </id>

    <property name="title"
    type="java.lang.String"
    update="true"
    insert="true"
    column="TITULO" />

    <property name="numero"
    type="int"
    update="true"
    insert="true"
    column="NUM_EVENTO" />
    </class>
    </hibernate-mapping>


    This is my application context XML file:
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

    <beans>

    <!-- JNDI DataSource for J2EE environments -->
    <bean id="testDataSource" class="org.springframework.jndi.JndiObjectFactoryB ean">
    <property name="jndiName" value="env/jdbc/TestDS"/>
    </bean>

    <!-- Hibernate SessionFactory -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSes sionFactoryBean">
    <property name="dataSource" ref="testDataSource"/>
    <property name="mappingResources">
    <value>com/sqs/pruebas/domain/event/Evento.hbm.xml</value>
    </property>
    <property name="hibernateProperties">
    <props>
    <prop key="hibernate.dialect">org.hibernate.dialect.Orac le9Dialect</prop>
    <prop key="hibernate.show_sql">true</prop>
    <prop key="hibernate.generate_statistics">true</prop>
    </props>
    </property>
    </bean>

    <!-- Transaction manager for a single Hibernate SessionFactory (alternative to JTA) -->
    <bean id="transactionManager" class="org.springframework.orm.hibernate3.Hibernat eTransactionManager">
    <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

    <bean id="eventoDAO" class="com.sqs.pruebas.model.dao.event.EventoDAOIm pl">
    <property name="sessionFactory" ref="sessionFactory"/>
    </bean>
    </beans>

    Find attached log file.

    Is there any configuration errors?
    Why sessionFactory value is always null?

    Thanks in advance,
    Antonio.
    Attached Files Attached Files

  2. #2
    Join Date
    Aug 2004
    Posts
    2,715

    Default

    Although you inherit from HibernateDaoSupport, you seem to have an own SessionFactoryProperty. Remove that (and all methods belonging to it). Then everything should work.

    Besides that: Please use [ c o d e ] [ / c o d e ] tags (without the in-between blanks) around your code, configuration and traces you post here. You might have noticed that postings tend to be hard to read otherwise.

    Regards,
    Andreas

  3. #3
    Join Date
    Aug 2006
    Posts
    9

    Default

    Thanks for your reply and sorry for my lack of code tag. I have discoverd it after I was sent my post.

    Theses are the data that should be tagged in my first post.

    Mapping file (generated with XDoclet):
    Code:
    <?xml version="1.0" encoding="UTF-8"?>
    
    <!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
    
    <hibernate-mapping
    >
        <class
            name="com.sqs.pruebas.domain.event.Evento"
            table="EVENTOS"
        >
    
            <id
                name="id"
                column="ID_EVENTO"
                type="java.lang.String"
            >
                <generator class="native">
                  <!--  
                      To add non XDoclet generator parameters, create a file named 
                      hibernate-generator-params-Evento.xml 
                      containing the additional parameters and place it in your merge dir. 
                  --> 
                </generator>
            </id>
    
            <property
                name="title"
                type="java.lang.String"
                update="true"
                insert="true"
                column="TITULO"
            />
    
            <property
                name="numero"
                type="int"
                update="true"
                insert="true"
                column="NUM_EVENTO"
            />
    
            <!--
                To add non XDoclet property mappings, create a file named
                    hibernate-properties-Evento.xml
                containing the additional properties and place it in your merge dir.
            -->
    
        </class>
    
    </hibernate-mapping>
    Application context XML file:
    Code:
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
    
      
      <!-- JNDI DataSource for J2EE environments -->
      <bean id="testDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
        <property name="jndiName" value="env/jdbc/TestDS"/>
      </bean>
      
      <!-- Hibernate SessionFactory -->
      <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="testDataSource"/>
        <property name="mappingResources">
          <value>com/sqs/pruebas/domain/event/Evento.hbm.xml</value>
        </property>
        <property name="hibernateProperties">
          <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.generate_statistics">true</prop>
          </props>
        </property>
      </bean>
      
      <!-- Transaction manager for a single Hibernate SessionFactory (alternative to JTA) -->
      <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
      </bean>
      
      <bean id="eventoDAO" class="com.sqs.pruebas.model.dao.event.EventoDAOImpl">
        <property name="sessionFactory" ref="sessionFactory"/>
      </bean>
    </beans>
    I don't know exactly what you mean with "you seem to have an own SessionFactoryProperty".

    I have changed my code removing all that seems to be unnecesary but sessionfactory is still null.

    My new code:
    Code:
    package com.sqs.pruebas.model.dao.event;
    
    import java.util.Collection;
    
    import java.util.List;
    
    import org.springframework.dao.DataAccessException;
    import org.springframework.dao.DataRetrievalFailureException;
    import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
    
    public class EventoDAOImpl extends HibernateDaoSupport implements EventoDAO {
      
      public EventoDAOImpl()  {
      }
      
      public Collection loadEventosById(String idEvento) throws DataAccessException {
        Session session = getSession();
        // session is null
        List result = session.createQuery("from Evento evento where evento.id=?").setParameter(0, idEvento).list();
        if (result == null) {
          throw new DataRetrievalFailureException("");
        }
        return result;
      }
    }
    Thanks,
    Antonio.

  4. #4
    Join Date
    Aug 2004
    Posts
    2,715

    Default

    Is the sessionFactory property of HibernateDaoSupport null or does the invocation of getSession() return null?
    From the log excerpt you posted one can see that a SessionFactory gets instantiated and the setter method is being invoked.

    If the session is null: Maybe there is no transaction defined.

    Regards,
    Andreas

  5. #5
    Join Date
    Aug 2006
    Posts
    9

    Default

    The invocation of getSession() return null.

    Thanks.

  6. #6
    Join Date
    Aug 2006
    Posts
    9

    Default

    Hi:

    After reading your recommendation and change my application context configuration file in order to use transactions, NullpointerExcption is still threw in the same point as before.

    My new appContext.xml is this:
    Code:
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
    
    <beans>
      <!-- JNDI DataSource for J2EE environments -->
      <bean id="testDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
        <property name="jndiName" value="env/jdbc/TestDS"/>
      </bean>
      
      <!-- Hibernate SessionFactory -->
      <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="testDataSource"/>
        <property name="mappingResources">
          <value>com/sqs/pruebas/domain/event/Evento.hbm.xml</value>
        </property>
        <property name="hibernateProperties">
          <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.generate_statistics">true</prop>
          </props>
        </property>
      </bean>
      
      <!-- Transaction manager that delegates to JTA (for a transactional JNDI DataSource) -->
      <bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager"/>
      
      <bean id="eventoDAO" class="com.sqs.pruebas.model.dao.event.EventoDAOImpl">
        <property name="sessionFactory" ref="sessionFactory"/>
      </bean>
      
      <bean id="eventoTx" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
        <property name="transactionManager" ref="transactionManager"/>
        <property name="target" ref="eventoDAO"/>
        <property name="transactionAttributes">
          <props>
            <prop key="load*">PROPAGATION_REQUIRED,readOnly</prop>
          </props>
        </property>
      </bean>
    </beans>
    Maybe the stack trace could help to find out the solution:
    Code:
    2006-08-02 08:23:54,062 - DEBUG - Could not complete request
    java.lang.NullPointerException
    	at org.springframework.orm.hibernate3.support.HibernateDaoSupport.getSession(HibernateDaoSupport.java:141)
    	at com.sqs.pruebas.model.dao.event.EventoDAOImpl.loadEventosById(EventoDAOImpl.java:29)
    	at com.sqs.pruebas.control.web.notif.NotificacionController.handleRequest(NotificacionController.java:35)
    	at org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:44)
    	at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:723)
    	at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:663)
    	at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:394)
    	at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:348)
    	at javax.servlet.http.HttpServlet.service(HttpServlet.java:743)
    	at javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
    	at com.evermind.server.http.ServletRequestDispatcher.invoke(ServletRequestDispatcher.java:719)
    	at com.evermind.server.http.ServletRequestDispatcher.forwardInternal(ServletRequestDispatcher.java:376)
    	at com.evermind.server.http.HttpRequestHandler.doProcessRequest(HttpRequestHandler.java:870)
    	at com.evermind.server.http.HttpRequestHandler.processRequest(HttpRequestHandler.java:451)
    	at com.evermind.server.http.HttpRequestHandler.serveOneRequest(HttpRequestHandler.java:218)
    	at com.evermind.server.http.HttpRequestHandler.run(HttpRequestHandler.java:119)
    	at com.evermind.server.http.HttpRequestHandler.run(HttpRequestHandler.java:112)
    	at oracle.oc4j.network.ServerSocketReadHandler$SafeRunnable.run(ServerSocketReadHandler.java:260)
    	at com.evermind.util.ReleasableResourcePooledExecutor$MyWorker.run(ReleasableResourcePooledExecutor.java:303)
    	at java.lang.Thread.run(Thread.java:595)
    2006-08-02 08:23:54,093 - DEBUG - Publishing event in context [WebApplicationContext for namespace 'pruebas-control-servlet']: RequestHandledEvent: url=[/pruebas/notif.htm]; time=[31843ms]; client=[10.8.196.159]; method=[GET]; servlet=[pruebas-control]; session=[null]; user=[null]; status=[failed: java.lang.NullPointerException]
    2006-08-02 08:23:54,093 - DEBUG - Publishing event in context [Root WebApplicationContext]: RequestHandledEvent: url=[/pruebas/notif.htm]; time=[31843ms]; client=[10.8.196.159]; method=[GET]; servlet=[pruebas-control]; session=[null]; user=[null]; status=[failed: java.lang.NullPointerException]
    2006-08-02 08:23:54.218 NOTIFICATION  J2EE JSP0008 Unable to dispatch JSP Page : java.io.FileNotFoundException: D:\Documentos ACV\Personal\Trabajo\CDP\dev\pruebas\pruebas\pruebas-war\public-html\WEB-INF\jsp\error.jsp (El sistema no puede hallar el archivo especificado.
    )
    	at java.io.FileInputStream.open(Native Method)
    	at java.io.FileInputStream.<init>(FileInputStream.java:106)
    	at java.io.FileInputStream.<init>(FileInputStream.java:66)
    	at oracle.jsp.provider.JspFilesystemResource.fromStream(JspFilesystemResource.java:150)
    	at oracle.jsp.parse.XMLUtil.getFromStream(XMLUtil.java:228)
    	at oracle.jsp.runtimev2.JspPageCompiler.compilePage(JspPageCompiler.java:341)
    	at oracle.jsp.runtimev2.JspPageInfo.compileAndLoad(JspPageInfo.java:610)
    	at oracle.jsp.runtimev2.JspPageTable.compileAndServe(JspPageTable.java:634)
    	at oracle.jsp.runtimev2.JspPageTable.service(JspPageTable.java:370)
    	at oracle.jsp.runtimev2.JspServlet.internalService(JspServlet.java:478)
    	at oracle.jsp.runtimev2.JspServlet.service(JspServlet.java:401)
    	at javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
    	at com.evermind.server.http.ServletRequestDispatcher.invoke(ServletRequestDispatcher.java:719)
    	at com.evermind.server.http.ServletRequestDispatcher.forwardInternal(ServletRequestDispatcher.java:376)
    	at com.evermind.server.http.ServletRequestDispatcher.unprivileged_forward(ServletRequestDispatcher.java:270)
    	at com.evermind.server.http.ServletRequestDispatcher.access$100(ServletRequestDispatcher.java:42)
    	at com.evermind.server.http.ServletRequestDispatcher$2.oc4jRun(ServletRequestDispatcher.java:204)
    	at oracle.oc4j.security.OC4JSecurity.doPrivileged(OC4JSecurity.java:283)
    	at com.evermind.server.http.ServletRequestDispatcher.forward(ServletRequestDispatcher.java:209)
    	at com.evermind.server.http.EvermindHttpServletResponse.handleException(EvermindHttpServletResponse.java:1599)
    	at com.evermind.server.http.EvermindHttpServletResponse.handleException(EvermindHttpServletResponse.java:1501)
    	at com.evermind.server.http.HttpRequestHandler.doProcessRequest(HttpRequestHandler.java:877)
    	at com.evermind.server.http.HttpRequestHandler.processRequest(HttpRequestHandler.java:451)
    	at com.evermind.server.http.HttpRequestHandler.serveOneRequest(HttpRequestHandler.java:218)
    	at com.evermind.server.http.HttpRequestHandler.run(HttpRequestHandler.java:119)
    	at com.evermind.server.http.HttpRequestHandler.run(HttpRequestHandler.java:112)
    	at oracle.oc4j.network.ServerSocketReadHandler$SafeRunnable.run(ServerSocketReadHandler.java:260)
    	at com.evermind.util.ReleasableResourcePooledExecutor$MyWorker.run(ReleasableResourcePooledExecutor.java:303)
    	at java.lang.Thread.run(Thread.java:595)
    And reviewing my logs, I've seen some 'suspicious' lines (find attached all the log lines referred to sessionFactory).

    In the logs, it seems to be that sessionFactory is created correctly, but just before mapp Evento object to relational columns, it says 'Building new Hibernate SessionFactory'. Maybe this new instance of sessionFactory the null one that I receive in the DAO?
    Also there is a line that says 'Not binding factory to JNDI, no JNDI name configured' just when it's trying to create/instatiate the session factory after or during the mapping tasks. After that it instatiates the DAO bean and invokes the set methods in order to inject other bean definitions and seems to work correctly.

    Also, at the first lines says "Rejected bean name 'sessionFactory'" after preinstatiating singletons, but I dont know if this is concerning or not.

    Thanks,
    Antonio.
    Attached Files Attached Files

  7. #7
    Join Date
    Aug 2004
    Posts
    2,715

    Default

    I didn't find somethig problematic in the log. However, as I see you define a transaction manager bean, but I do not see where it is actually used.
    Did you apply declarative transaction proxies somewhere? Or do you use TransactionTemplate in your code?

    Regards,
    Andreas

  8. #8
    Join Date
    Aug 2006
    Posts
    9

    Default

    I am using declarative way of transaction (I think so). I have included the transaction proxy in the application context xml file. This is the code, or is it bad?
    Code:
      <bean id="eventoTx" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
        <property name="transactionManager" ref="transactionManager"/>
        <property name="target" ref="eventoDAO"/>
        <property name="transactionAttributes">
          <props>
            <prop key="load*">PROPAGATION_REQUIRED,readOnly</prop>
          </props>
        </property>
      </bean>
    Do you have any idea what to change in my code in order to see Hibernate working with Spring?

    Thanks for your help and interest,
    Antonio.

  9. #9
    Join Date
    Aug 2004
    Posts
    2,715

    Default

    Usually it is recommended to apply transactional boundaries at the business layer, not the DAO layer. Though, technically, your configuration is ok so far (I seem to have missed that part in your previous post).
    I take it you access the "eventoTx" bean and not "eventoDAO"? Otherwise the proxy would have no effect. Can you post the configuration/code where the DAO is referred to/retrieved?

    Regards,
    Andreas

  10. #10
    Join Date
    Aug 2006
    Posts
    9

    Default

    I know what you have mentioned about business and DAO layer, but this is my first example with Spring + Hibernate and I only wanted to send a request form a browser that response a list of data from the database, using a Spring Controller that invokes directly the DAO that retrieves data using Hibernate.

    I cannot understand what you want to say in your sentence:
    I take it you access the "eventoTx" bean and not "eventoDAO"?
    My bean and transaction configuration have been "inspired" in the petClinic sample.
    Code:
    	<bean id="clinicTarget" class="org.springframework.samples.petclinic.hibernate.HibernateClinic">
    		<property name="sessionFactory" ref="sessionFactory"/>
    	</bean>
    
    	<bean id="clinic" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
    		<property name="transactionManager" ref="transactionManager"/>
    		<property name="target" ref="clinicTarget"/>
    		<property name="transactionAttributes">
    			<props>
    				<prop key="get*">PROPAGATION_REQUIRED,readOnly</prop>
    				<prop key="find*">PROPAGATION_REQUIRED,readOnly</prop>
    				<prop key="load*">PROPAGATION_REQUIRED,readOnly</prop>
    				<prop key="store*">PROPAGATION_REQUIRED</prop>
    			</props>
    		</property>
    	</bean>
    Respect to my configuration and code, in my web.xml I use the ContextLoaderListener to load some config application context, one per layer and a DispatchServlet to implement the MVC pattern.

    Code:
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/pruebas-webflows.xml, /WEB-INF/pruebas-service.xml,/WEB-INF/pruebas-data-hibernate.xml, /WEB-INF/pruebas-security.xml</param-value>
      </context-param>
    ...
      <listener>    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
      </listener>
    ...
      <servlet>
        <servlet-name>pruebas-control</servlet-name>    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
      </servlet>
      
      <servlet-mapping>
        <servlet-name>pruebas-control</servlet-name>
        <url-pattern>*.htm</url-pattern>
      </servlet-mapping>
    This is the pruebas-control-servlet.xml file:

    Code:
    <beans>  
    
      <bean id="eventoController" class="com.sqs.pruebas.control.web.event.EventoController">
      </bean>
      
      <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="urlMap">
          <map>
            <entry key="/evento.htm">
              <ref bean="eventoController" />
            </entry>
          </map>
        </property>
      </bean>
      
      <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"><value>org.springframework.web.servlet.view.JstlView</value></property>
        <property name="prefix"><value>/jsp/</value></property>
        <property name="suffix"><value>.jsp</value></property>
      </bean>     
    </beans>
    This is the class EventoController which instantiate the DAO (should be the service class):

    Code:
    package com.sqs.pruebas.control.web.event;
    
    import com.sqs.pruebas.domain.event.Evento;
    import com.sqs.pruebas.model.dao.event.EventoDAOImpl;
    
    import java.util.Collection;
    import java.util.Iterator;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    import org.apache.log4j.PropertyConfigurator;
    
    import org.springframework.web.servlet.ModelAndView;
    import org.springframework.web.servlet.mvc.Controller;
    
    
    public class EventoController implements Controller {
    
      public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) {
        PropertyConfigurator.configure(NotificacionController.class.getResource("/config/log4j.properties"));  
        Log log = LogFactory.getLog(NotificacionController.class);
        log.debug("....................................");
        EventoDAOImpl evDAO = new EventoDAOImpl();
        Collection eventos = evDAO.loadEventosById("01");
        for(Iterator it=eventos.iterator(); it.hasNext(); ) {
          log.debug(((Evento)it.next()).toString());
        }
        log.debug("....................................");
        return new ModelAndView("/listaEventos");
      }
    }
    listaEventos.jsp only iterate over the result list of events obtain with the DAO (really only one event).

    The rest of the classes and XML files is in previous post.

    Thanks,
    Antonio.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •