Announcement Announcement Module
Collapse
No announcement yet.
Spring+Hibernate: SessionFactory is null :-( Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Spring+Hibernate: SessionFactory is null :-(

    Hi there,

    I just started on Spring, and this problem is driving me nuts: My SessionFactory just won't be anything but null....

    applicationContext.xml:
    Code:
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:util="http://www.springframework.org/schema/util"
           xmlns:tx="http://www.springframework.org/schema/tx"
           xmlns:jee="http://www.springframework.org/schema/jee"
           xmlns:aop="http://www.springframework.org/schema/aop"
    
           xsi:schemaLocation="
               http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
               http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
               http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd
               http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd">
    
        <!-- <context:annotation-config /> -->
        <!-- <context:mbean-export /> -->
    
        <!-- <jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/dataminer"/> -->
    
        <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
            <property name="jndiName" value="java:comp/env/jdbc/dataminer"/>
        </bean>
    
        <!--
            Create the JPA EntityManagerFactory
        -->
    
        <bean id="mySessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
            <property name="dataSource">
                <ref bean="dataSource"/>
            </property>
            <property name="annotatedClasses">
                <list>
                    <value>com.foo.dataminer.backend.entities.Accountsum</value>
                </list>
            </property>
            <property name="hibernateProperties">
                <props>
                    <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
                    <prop key="hibernate.show_sql">true</prop>
                    <prop key="hibernate.session_factory_name">java:comp/env/hibernate/sessionfactory</prop>
                </props>
            </property>
        </bean>
    
        <!--
        <bean id="mySessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
            <property name="dataSource">
                <ref local="dataSource"/>
            </property>
            <property name="mappingResources">
                <list>
                    <value>Accountsum.hbm.xml</value>
                </list>
            </property>
            <property name="hibernateProperties">
                <props>
                    <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
                    <prop key="hibernate.show_sql">true</prop>
                </props>
            </property>
        </bean>
        -->
    
        <bean id="myTxManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
            <property name="sessionFactory" ref="mySessionFactory"/>
            <property name="dataSource" ref="dataSource"/>
        </bean>
    
        <!--
        <bean id="myTxManager" class="org.springframework.transaction.jta.JtaTransactionManager"/>
        -->
    
        <bean id="hibernateInterceptor" class="org.springframework.orm.hibernate3.HibernateInterceptor">
            <property name="sessionFactory">
                <ref bean="mySessionFactory"/>
            </property>
        </bean>
    
        <bean id="accountsumAction" class="com.foo.dataminer.backend.actions.AccountsumActionImpl">
            <property name="sessionFactory"><ref bean="mySessionFactory"/></property>
            <!--<property name="transactionManager"><ref bean="myTxManager"/></property>-->
        </bean>
    
        <bean id="accountsum" class="org.springframework.aop.framework.ProxyFactoryBean">
            <property name="proxyInterfaces">
                <value>com.foo.dataminer.backend.actions.base.AccountsumAction</value>
            </property>
    
            <property name="interceptorNames">
                <list>
                    <value>hibernateInterceptor</value>
                    <value>accountsumAction</value>
                </list>
            </property>
        </bean>
    
    
    </beans>
    AccountsumActionImpl.java:
    Code:
    public class AccountsumActionImpl extends HibernateDaoSupport implements AccountsumAction {
    
        private final static Logger logger = LoggerFactory.getLogger(AccountsumActionImpl.class);
        
        @Override
        public Accountsum getAccountsumById(Long id) {
            try {
                logger.debug("Getting session...");
                logger.debug("SessionFactory is: " + this.getSessionFactory());
                // ************** ^^ THIS GIVES ME NULL ^^ *******************
                Session session = this.getSessionFactory().openSession();
                logger.debug("Session is: " + session);
                logger.debug("Creating query...");
                Query q = session.createQuery("from Accountsum a where a.id=:id");
                logger.debug("Query is: " + q);
                logger.debug("Setting query parameters...");
                q.setParameter("id", id, Hibernate.LONG);
                logger.debug("Getting single result...");
                return (Accountsum)q.uniqueResult();
            }
            catch (Exception e) {
                logger.error("Could not get accountsum!", e);
                return null;
            }
        }
    }
    I have this in web.xml:
    Code:
    ............
        <listener>
        	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
    ............
    Container is Tomcat 6. In server.xml I have this in the "GlobalNamingResources" section:
    Code:
        <Resource name="jdbc/dataminer" auth="Container"
                  type="javax.sql.DataSource" driverClassName="oracle.jdbc.OracleDriver"
                  url="jdbc:oracle:thin:@10.0.0.177:1521:test"
                  username="test" password="test"
                  maxActive="50" maxIdle="5"  initialSize="10"
                  maxWait="-1" removeAbandoned="true"
                  validationQuery="select 1 from dual"/>
    ...and this in context.xml:
    Code:
        <ResourceLink name="jdbc/dataminer"
                      global="jdbc/dataminer"
                      type="javax.sql.DataSource"/>
    Does anybody have a clue on this?

    Best regards,

    ~Silverjam

  • #2
    First off all your code is a disaster waiting to happen, you use openSession which by passes all spring mechanism and you endup with sessione everywhere, which after 50 times will grind your application to a hold (no more connections in your pool).

    You are using Spring 2.5 then also use the best practices from that approach. First refactor your action.

    Code:
    public class AccountsumActionImpl implements AccountsumAction {
    
        private final static Logger logger = LoggerFactory.getLogger(AccountsumActionImpl.class);
        
    	private SessionFactory sf;
    	
    	public setSessionFactory(SessionFactory sf) {
    		this.sf=sf;
    	}
    	
        @Override
        public Accountsum getAccountsumById(Long id) {
    		logger.debug("Getting session...");
    		logger.debug("SessionFactory is: " + sf);
    		// ************** ^^ THIS GIVES ME NULL ^^ *******************
    		Session session = sf.getCurrentSession();
    		logger.debug("Session is: " + session);
    		logger.debug("Creating query...");
    		Query q = session.createQuery("from Accountsum a where a.id=:id");
    		logger.debug("Query is: " + q);
    		logger.debug("Setting query parameters...");
    		q.setParameter("id", id, Hibernate.LONG);
    		logger.debug("Getting single result...");
    		return (Accountsum)q.uniqueResult();
        }
    }
    Next use the Spring 2.5 aop namespace (which you tried to use judging from your xml declaration) and remove some configuration (why do you give a name this will try to do something with jndi?!).

    Code:
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:util="http://www.springframework.org/schema/util"
           xmlns:tx="http://www.springframework.org/schema/tx"
           xmlns:jee="http://www.springframework.org/schema/jee"
           xmlns:aop="http://www.springframework.org/schema/aop"
    
           xsi:schemaLocation="
               http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
               http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
               http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
               http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
               http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd
               http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd">
    
        <!-- <context:annotation-config /> -->
        <!-- <context:mbean-export /> -->
    
        <jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/dataminer"/>
    
        <!--
            Create the JPA EntityManagerFactory
        -->
    
    	<tx:advice id="txAdvice" transaction-manager="myTxManager">
    		<tx:attributes>
    			<tx:method name="*"/>
    		</tx:attributes>
    	</tx:advice>
    
    	<!--
    	Apply transactions to everything in any package that extends a class that ends with Action.
    	-->
    	<aop:config>
    		<aop:pointcut id="actionMethod" expression="* *..*Action+.*(..))"/>
    		<aop:advice pointcut-ref="actionMethod" advice-ref="txAdvice" />
    	</aop:config>
    
        <bean id="mySessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
            <property name="dataSource" ref='"dataSource" />
            <property name="annotatedClasses">
                <list>
                    <value>com.foo.dataminer.backend.entities.Accountsum</value>
                </list>
            </property>
            <property name="hibernateProperties">
                <props>
                    <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
                    <prop key="hibernate.show_sql">true</prop>
                </props>
            </property>
        </bean>
    
        <bean id="myTxManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
            <property name="sessionFactory" ref="mySessionFactory"/>
            <property name="dataSource" ref="dataSource"/>
        </bean>
    
        <bean id="accountsum" class="com.foo.dataminer.backend.actions.AccountsumActionImpl">
            <property name="sessionFactory"><ref bean="mySessionFactory"/></property>
        </bean>
    
    
    </beans>
    However this probably does not solve your problem but gives you best practices and a reduced configuration .

    Your problem arises I guess from the fact that you are creating a new instance of the AccountsumActionImpl yourself whereas you should use the one configured in the application context.

    Comment


    • #3
      Solved!

      I know that the code sucks, but I was just trying to get anything out.

      Anyway: The problem was somewhere else. I am running JSF (didn't mention that in the original post), so I added this to faces-config.xml:

      Code:
      <el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
      Finally I hooked the Spring bean (AccountsumActionImpl) onto the JSF managed bean as a managed property, so now it finally gives me something.

      AccountsumActionImpl.java now looks like this:
      Code:
      public class AccountsumActionImpl extends HibernateDaoSupport implements AccountsumAction, Serializable {
          
          @Override
          public Accountsum getAccountsumById(Long id) {
              try {
                  return (Accountsum)this.getSession().createQuery("from Accountsum a where a.id=:id").setParameter("id", id, Hibernate.LONG).uniqueResult();
              }
              catch (Exception e) {
                  e.printStacktrace();
                  return null;
              }
          }
      }
      Now for the fun part!

      BTW: Any good leads on how to structure things when doing Spring and JSF?

      Comment


      • #4
        Spring+Hibernate: SessionFactory is null :-(

        can bring the complete solution?

        Originally posted by silverjam View Post
        I know that the code sucks, but I was just trying to get anything out.

        Anyway: The problem was somewhere else. I am running JSF (didn't mention that in the original post), so I added this to faces-config.xml:

        Code:
        <el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>

        Finally I hooked the Spring bean (AccountsumActionImpl) onto the JSF managed bean as a managed property, so now it finally gives me something.

        AccountsumActionImpl.java now looks like this:
        Code:
        public class AccountsumActionImpl extends HibernateDaoSupport implements AccountsumAction, Serializable {
            
            @Override
            public Accountsum getAccountsumById(Long id) {
                try {
                    return (Accountsum)this.getSession().createQuery("from Accountsum a where a.id=:id").setParameter("id", id, Hibernate.LONG).uniqueResult();
                }
                catch (Exception e) {
                    e.printStacktrace();
                    return null;
                }
            }
        }
        Now for the fun part!

        BTW: Any good leads on how to structure things when doing Spring and JSF?

        Comment


        • #5
          Code:
          public class AccountsumActionImpl extends HibernateDaoSupport implements AccountsumAction, Serializable {
              
              @Override
              public Accountsum getAccountsumById(Long id) {
                  try {
                      return (Accountsum)this.getSession().createQuery("from Accountsum a where a.id=:id").setParameter("id", id, Hibernate.LONG).uniqueResult();
                  }
                  catch (Exception e) {
                      e.printStacktrace();
                      return null;
                  }
              }
          }
          Don't use getSession that will give you an unmanaged session either use the sessionfactory and call getCurrentSession or use a hibernatetemplate with a HibernateCallback.

          Comment


          • #6
            my problem is the same, sessionFactory is null, i call my method getAccountsumById from a JSF Manage Bean... but the sessionFactory always is null

            this is my aplication context

            Code:
            <beans xmlns="http://www.springframework.org/schema/beans"
            	xmlns:security="http://www.springframework.org/schema/security"
            	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
            	xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util"
            	xmlns:jee="http://www.springframework.org/schema/jee" xmlns:aop="http://www.springframework.org/schema/aop"
            	xmlns:tx="http://www.springframework.org/schema/tx"
            	xsi:schemaLocation="http://www.springframework.org/schema/beans
                   http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
                   http://www.springframework.org/schema/aop 
                   http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
                   http://www.springframework.org/schema/tx
                   http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
                   http://www.springframework.org/schema/security 
                   http://www.springframework.org/schema/security/spring-security-2.0.1.xsd
                   http://www.springframework.org/schema/context
                   http://www.springframework.org/schema/context/spring-context-2.5.xsd
                   http://www.springframework.org/schema/util
                   http://www.springframework.org/schema/util/spring-util-2.5.xsd
                   http://www.springframework.org/schema/jee
                   http://www.springframework.org/schema/jee/spring-jee-2.5.xsd">
            	
            	<!--
            		========================= HIBERNATE DEFINITIONS
            		=========================
            	-->
            
            	<!--
            		Transaction manager for a single Hibernate SessionFactory (alternative
            		to JTA)
            	-->
            	<bean id="transactionManager"
            		class="org.springframework.orm.hibernate3.HibernateTransactionManager">
            		<property name="sessionFactory">
            			<ref local="sessionFactory" />
            		</property>
            	</bean>
            
            	<bean id="dataSource"
            		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
            		<property name="url" value="jdbc:mysql://localhost/dbname" />
            		<property name="username" value="hibernate" />
            		<property name="password" value="hibernate" />
            	</bean>
            
            	<bean id="sessionFactory"
            		class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
            		<property name="dataSource">
            			<ref local="dataSource" />
            		</property>
            		<property name="mappingResources">
            			<list>
            				<value>org/jp/core/persistence/pojo/xml/CatLocation.hbm.xml
            				</value>
            			</list>
            		</property>
            		<property name="hibernateProperties">
            			<props>
            				<!-- <prop key="hibernate.hbm2ddl.auto">update</prop>-->
            				<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect
            				</prop>
            				<prop key="hibernate.show_sql">true</prop>
            				<prop key="hbm2java">update</prop>
            			</props>
            		</property>
            	</bean>
            
            	<!--
            		========================= BUSINESS OBJECT DEFINITIONS
            		=========================
            	-->
            	
            	<bean id="catLocationDaoImp" class="org.jp.core.persistence.dao.CatLocationDaoImp">
            		<property name="sessionFactory">
            			<ref local="sessionFactory" />
            		</property>
            	</bean>
            
            	<!--
            		========================= SECURITY OBJECT DEFINITIONS
            		=========================
            	-->
            
            	<security:http auto-config="true">
            		<security:intercept-url pattern="/login*"
            			access="IS_AUTHENTICATED_ANONYMOUSLY" />
            		<security:intercept-url pattern="/j_spring_security_switch_user"
            			access="ROLE_SUPERVISOR" />
            		<security:intercept-url pattern="/pages/**"
            			access="ROLE_USER" />
            		<security:intercept-url pattern="/templates/**"
            			access="ROLE_ADMIN" />
            		<security:form-login login-page="/login.me"
            			login-processing-url="/j_spring_security_check" default-target-url='/pages/index.me'
            			authentication-failure-url="/login.me?login_error=1" />
            		<security:logout logout-url="/logout"
            			logout-success-url="/" />
            	</security:http>
            	<security:authentication-provider>
            		<security:user-service>
            			<security:user name="jpicado" password="demodemo"
            				authorities="ROLE_USER, ROLE_ADMIN" />
            			<security:user name="user" password="demodemo"
            				authorities="ROLE_USER" />
            		</security:user-service>
            	</security:authentication-provider>
            	<bean id="springSecurityFilterChain" class="org.springframework.security.util.FilterChainProxy">
            		<security:filter-chain-map path-type="ant">
            			<security:filter-chain pattern="/**" filters="sif" />
            		</security:filter-chain-map>
            	</bean>
            	<bean id="sif"
            		class="org.springframework.security.context.HttpSessionContextIntegrationFilter" />
            	
            </beans>

            Code:
            public class CatLocationDaoImp  implements ICatLocDao {
            
            	private HibernateTemplate hibernateTemplate;
            	private static Logger log = Logger.getLogger(CatLocationDaoImp.class);
            
            	private SessionFactory sessionFactory;
            
            	public CatLocationDaoImp() {
            		// TODO Auto-generated constructor stub
            	}
            	public SessionFactory getSessionFactory() {
            		return sessionFactory;
            	}
            
            	public void setSessionFactory(SessionFactory sessionFactory) {
            		this.sessionFactory = sessionFactory;
            	}
            
            	
            	public List<CatLocation> getAccountsumById() {
            		log.info("Getting session1...");
            		log.info("error getSessionFactory-> " + this.sessionFactory); // ---> THIS IS NULL ALWAYS!!
            		try {
            			log.info("createQuery");
            			return this.sessionFactory.getCurrentSession().createQuery("from CatLocation").list();
            
            		} catch (Exception e) {
            			log.fatal("error getAccountsumById-> " + e);
            			return null;
            		}
            	}	
            
            }
            my log

            Code:
            INFO,ContextLoader,ContainerBackgroundProcessor[StandardEngine[Catalina]]] Root WebApplicationContext: initialization started
            [INFO,XmlWebApplicationContext,ContainerBackgroundProcessor[StandardEngine[Catalina]]] Refreshing [email protected]a22e0c: display name [Root WebApplicationContext]; startup date [Fri Apr 24 11:36:21 CST 2009]; root of context hierarchy
            [INFO,XmlBeanDefinitionReader,ContainerBackgroundProcessor[StandardEngine[Catalina]]] Loading XML bean definitions from ServletContext resource [/WEB-INF/applicationContext.xml]
            [INFO,XmlWebApplicationContext,ContainerBackgroundProcessor[StandardEngine[Catalina]]] Bean factory for application context [[email protected]a22e0c]: org.springframework.beans.factory.support.DefaultListableBeanFactory@1ea2de1
            [INFO,DefaultListableBeanFactory,ContainerBackgroundProcessor[StandardEngine[Catalina]]] Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1ea2de1: defining beans [transactionManager,dataSource,sessionFactory,catLocationDaoImp,_authenticationManager,_filterChainProxy,_httpSessionContextIntegrationFilter,_filterChainProxyPostProcessor,_filterChainList,_securityContextHolderAwareRequestFilter,_accessManager,_portMapper,_exceptionTranslationFilter,_filterSecurityInterceptor,_sessionFixationProtectionFilter,_anonymousProcessingFilter,_rememberMeServices,_rememberMeFilter,_rememberMeServicesInjectionBeanPostProcessor,_logoutFilter,_basicAuthenticationEntryPoint,_basicAuthenticationFilter,_formLoginFilter,_formLoginEntryPoint,_entryPointInjectionBeanPostProcessor,_userServiceInjectionPostProcessor,org.springframework.security.providers.dao.DaoAuthenticationProvider#0,_userDetailsService,org.springframework.security.config.AuthenticationProviderBeanDefinitionParser$AuthenticationProviderCacheResolver#0,springSecurityFilterChain,sif,barBean]; root of factory hierarchy
            [INFO,DriverManagerDataSource,ContainerBackgroundProcessor[StandardEngine[Catalina]]] Loaded JDBC driver: com.mysql.jdbc.Driver
            77 [ContainerBackgroundProcessor[StandardEngine[Catalina]]] INFO org.hibernate.cfg.Environment - Hibernate 3.3.1.GA
            83 [ContainerBackgroundProcessor[StandardEngine[Catalina]]] INFO org.hibernate.cfg.Environment - hibernate.properties not found
            87 [ContainerBackgroundProcessor[StandardEngine[Catalina]]] INFO org.hibernate.cfg.Environment - Bytecode provider name : javassist
            93 [ContainerBackgroundProcessor[StandardEngine[Catalina]]] INFO org.hibernate.cfg.Environment - using JDK 1.4 java.sql.Timestamp handling
            390 [ContainerBackgroundProcessor[StandardEngine[Catalina]]] INFO org.hibernate.cfg.HbmBinder - Mapping class: org.jp.core.persistence.pojo.CatLocation -> cat_location
            [INFO,LocalSessionFactoryBean,ContainerBackgroundProcessor[StandardEngine[Catalina]]] Building new Hibernate SessionFactory
            .......
            874 [ContainerBackgroundProcessor[StandardEngine[Catalina]]] INFO org.hibernate.cfg.SettingsFactory - Named query checking : enabled
            944 [ContainerBackgroundProcessor[StandardEngine[Catalina]]] INFO org.hibernate.impl.SessionFactoryImpl - building session factory
            ......
            
            [INFO,ContextLoader,ContainerBackgroundProcessor[StandardEngine[Catalina]]] Root WebApplicationContext: initialization completed in 2861 ms
            [INFO,CacheManager,ContainerBackgroundProcessor[StandardEngine[Catalina]]] Selected [org.ajax4jsf.cache.LRUMapCacheFactory] cache factory

            Comment

            Working...
            X