Announcement Announcement Module
Collapse
No announcement yet.
Using getHibernateTemplate() problem Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Using getHibernateTemplate() problem

    Hi,

    I'm a newbie to Spring. May be this question sound a childish, but still i need some help in this problem.

    In a DAO which extends HibernateDaoSupport, i have a method named findByProperty in which i call getHibernateTemplate().find(queryStr, value);

    The problem is i get a nullPointerException for getHibernateTemplate() method.
    I have defined a sessionFactory in application-context.xml. Also the DAO has a reference to the sessionFactory bean through sessionFactory property in the application-context.xml file.

    Wt can be the problem or do i miss anythg????

    I need some guidence in this problem.

    thanks in advance.

  • #2
    Typically these problems occur when either you haven't wired it up correctly or you're creating a new instance of the bean instead of actually using Spring. It might be useful to post your code and configuration all surrounded by [ code] [ /code] tags.

    Comment


    • #3
      Hi,

      Thanks a lot for your reply.

      Here is the relevent part of my application-context.xml file:

      Code:
          
              <bean id="sessionFactory"
      		class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
      		<property name="configLocation"
      			value="/WEB-INF/hibernate.cfg.xml">
      		</property>
      	</bean>
      
             <bean id="UsersDAO" class="com.acheivers.db.UsersDAO">
      		<property name="sessionFactory">
      			<ref bean="sessionFactory" />
      		</property>
             </bean>
      Here is the part of my Hibernate.cfg.xml which maps to the Users table for which UsersDAO is written

      Code:
         
       <hibernate-configuration>
      
      	<session-factory>
      		<property name="dialect">
      			org.hibernate.dialect.MySQLDialect
      		</property>
      		<property name="connection.url">
      			jdbc:mysql://localhost:3306/acheivers
      		</property>
      		<property name="connection.username">root</property>
      		<property name="connection.driver_class">
      			com.mysql.jdbc.Driver
      		</property>
      		<property name="myeclipse.connection.profile">
      			mysql-connector-5.0.5
      		</property>
      		<mapping class="com.acheivers.db.Users" />
      
      	</session-factory>
      
      </hibernate-configuration>
      In acheivers-servlet.xml (dispatcher servlet) i have defined this :
      Code:
          
       <bean name="jsp/login" class="com.acheivers.web.controllers.LoginController" />
      In the login controller i'm using the UsersDAO like this:

      Code:
         
       UsersDAO usd = new UsersDAO();
       List<Users> users = usd.findByProperty(str, str);
      In the UsersDAO the above called method is defined like this:
      Code:
          
           public List findByProperty(String propertyName, Object value) {
      
      		try {
      			String queryString = "from Users as model where model."
      					+ propertyName + "= ?";
      			return getHibernateTemplate().find(queryString, value);
      		} catch (RuntimeException re) {
      			log.error("find by property name failed", re);
      			throw re;
      		}
      	 }
      But i get a nullPointer on getHibernateTemplate() method. Why is that?? do i miss anythg???

      I read that HibernateDAOSupport can create a HibernateTemplate if sessonFactory is specified. I have defined sessionFactory in application-context.xml. Is that all i need to do??

      Please guide me and give an explanation. Sample codes will be much more helpful.

      Thanks a lot.

      Comment


      • #4
        This is a common problem when people start using Spring. If you use the new operator to create your DAO Spring doesn't know anything about it. If you're using Spring, you're passing over the control of creating new instances to it, thus you need to inject your reference into your controller with Spring instead of just creating a new instance.
        Code:
        UsersDAO usd = new UsersDAO();

        Comment


        • #5
          Hi,

          Thanks a lot Karl, it worked.

          I changed my code like this:
          Code:
           HttpSession session = request.getSession();
          		ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(session.getServletContext());
           
          UsersDAO usd = (UsersDAO)ctx.getBean("UsersDAO");
          and everythg is fine now. But still i have a question.....

          Am i doing it in the right way?
          Is there any other better ways to do this?

          Please give me an explanation....

          Thanks a lot.

          Comment


          • #6
            Well now instead of creating an instance, you are "looking it up" from the applicationContext. Instead of doing this, you could go one step further and inject the collaborator. So in your case inject your DAO into your Controller. You might not want to have your controller accessing your dao directly in the long term, but hopefully you get the idea.
            http://static.springsource.org/sprin...ns-ref-element

            Comment


            • #7
              karldmoore thanks for your reply.

              In my case I am injecting sessionFactory into DAO and dao into Service and service into controller, so now I am using new operator to create objects.

              Still I have this problem. sessionFactory is necessarily created in applicationContext.xml only or it can be anywhere?

              Because I have not created in appcontext.xml.

              Thanks
              Kumar

              Comment


              • #8
                Originally posted by vasukumar View Post
                Still I have this problem. sessionFactory is necessarily created in applicationContext.xml only or it can be anywhere? Because I have not created in appcontext.xml.
                Everything needs to be configured in the applicationContext. If you are still having problems, post the code and configuration (in [ code] [ /code] tags), that's causing this issue.

                Comment


                • #9
                  I just removed HibernateDaoSupport and created a sessionFactory, getter and serrter for that.

                  injected sessionFactory from applicationContext.xml to DAO, I put a condition in the set method to check the sessionFactory it is not null.

                  SESSION FACTORY IS NOT NULL org.hibernate.impl.SessionFactoryImpl@1582a7c


                  while accessing this I am getting null.

                  Code:
                  	private SessionFactory sessionFactory;
                  
                  	
                   /**
                  	 * @return the sessionFactory
                  	 */
                  	public Session getSession() {
                  		return sessionFactory.openSession();
                  	}
                  
                  	/**
                  	 * @param sessionFactory the sessionFactory to set
                  	 */
                  	public void setSessionFactory(SessionFactory sessionFactory) {
                  		if(null == sessionFactory) System.out.println("SESSION FACTORY IS NULL");
                  		System.out.println("SESSION FACTORY IS NOT NULL "+ sessionFactory);
                  		this.sessionFactory = sessionFactory;
                  	}

                  This is what I have put in the DAO. If you don't get any idea I will put the whole configuration and DAO in the next post.

                  Thanks
                  Kumar

                  Comment


                  • #10
                    It would be nice to see the whole thing, not really sure what's going on.

                    Comment


                    • #11
                      Sorry for troubling you, wasted your time and my time as well.

                      Got the problem, will manage this.

                      I need more information on solving my transactions, I will reply to other thread. i am going to change the implementaiton to spring version using hibernateTemplate(), so that we can configure transaction manager for the sessionFactory bean.

                      Thanks and sorry

                      Comment


                      • #12
                        Originally posted by vasukumar View Post
                        Thanks and sorry
                        Not a problem, glad you solved your problem ;-).

                        Comment


                        • #13
                          When I was working with one DAO it went well, when I created more DAOs in the same way and hitting query.list() throwing JDBC exception. ( Connection could not be created.).

                          I have to do some more tests to confirm where the problem is, if you have idea please provide me. I will post again if I am not able to solve it.


                          Steps are as follows.
                          1. dataSource created using DriverManagerDataSource
                          2. sessionFactory created using dataSource
                          3. injected sessionFactory to all DAO, which extends HibernateDaoSupport
                          4. using getSession().createQuery("query")
                          5. hitting query.list() throws JDBC Exception saying Connection can not be created.

                          Thanks
                          Kumar

                          Comment


                          • #14
                            Originally posted by vasukumar View Post
                            dataSource created using DriverManagerDataSource
                            I'd suggest that you use a proper connection pool instead of the this data source, it's going to create a new connection everytime.

                            Comment


                            • #15
                              Oh, then can I use commons DBCP, is it good to use?

                              Thanks
                              kumar

                              Comment

                              Working...
                              X