user3205761
user3205761

Reputation: 311

NullPointException with Hibernate 4 and Spring 3.0.5 Intergration

I tried to create a Java program using Hibernate 4.1.6 and Spring 3.0.5. When i ran my app throwing NULLPOINT EXCEPTION. Anyone help me, please,

  1. SpringBeans.xml:

    http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

    <!-- Database Configuration -->
    <import resource="config/spring/DataSource.xml"/>
    <import resource="config/spring/HibernateSessionFactory.xml"/>
    
    <!-- Beans Declaration -->
    <import resource="config/spring/UserBeans.xml"/>
    

    2. HibernateSessionFactory.xml
    

    <property name="dataSource">
      <ref bean="dataSource"/>
    </property>
    
    <property name="hibernateProperties">
       <props>
         <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
         <prop key="hibernate.show_sql">true</prop>
       </props>
    </property>
    
    <property name="mappingResources">
        <list>
          <value>com/model/TblUser.hbm.xml</value>
        </list>
    </property> 
    

  2. DataSource.xml

    WEB-INF/classes/config/database/properties/database.properties

  3. database.properties

    jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql:localhost:3306/auction_nms jdbc.username=root jdbc.password=root

  4. UserBeans.xml

    <!-- User business object -->
    

  5. UserDaoImpl .java

    public class UserDaoImpl implements UserDao { @Autowired SessionFactory sessionFactory;

    /*
     * @see com.dao.UserDao#save(com.model.TblUser)
     */
    @Override
    public void save(TblUser user) {
        sessionFactory.getCurrentSession().save(user);
    }
    

7.App.java

public class App {

    // get log4j handler
    private static final Logger logger = Logger.getLogger(App.class);

    static TblUser              user   = new TblUser(2, "2", "2");

    public static void main(String[] args) {
        try {
            UserDao userDao = new UserDaoImpl();
            userDao.save(user);
        } catch (Exception e) {
            System.err.`enter code here`println(e);
        } finally {
            if (logger.isDebugEnabled()) {
                logger.debug(user);
            }
        }
    }
}

Thank you very much!!!

Upvotes: 0

Views: 219

Answers (1)

Hrishikesh
Hrishikesh

Reputation: 2053

You are creating the UserDAO object by using the new keyword. You should start the spring container by loading the appContext, in your case SpringBeans.xml. If you use the new keyword Spring doesnt manage your dependencies, hence, your sessionFactory is never injected into the DAO instance.

This should be the contents of you main() instead of the current ones.

ApplicationContext appContext = new ClassPathXmlApplicationContext(new String[] {
        "classpath*:/META-INF/SpringBeans.xml"
        });
appContext.getBean("userDao");

.. call your save on it.

Upvotes: 3

Related Questions