日期:2014-05-20  浏览次数:20814 次

hibernatetemplate的错误,求教高手
test.java
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.yiyi.shop.DAO.UserDao;
import com.yiyi.shop.domain.User;
public class UnitTest {

public static void main(String args[]){
ApplicationContext acx = new ClassPathXmlApplicationContext("applicationContext.xml");
UserDao userdao = (UserDao) acx.getBean("userdao");
User user = new User();
user.setUsername("sdy");
user.setPassword("123456");
user.setTelephone("12396689548");
user.setEmail("dsad@hotmai.com");
user.setAddress("中国");
userdao.saveUser(user);
}

}
applicationContext.xml里的配置

  <bean id="userdao" class="com.yiyi.shop.DAO.impl.UserDaoImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>


package com.yiyi.shop.DAO.impl;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.HibernateTemplate;

import com.yiyi.shop.DAO.UserDao;
import com.yiyi.shop.domain.User;

public class UserDaoImpl implements UserDao {

private SessionFactory sessionFactory;

private HibernateTemplate hibernatetemplate;



/**
* @return the template
*/
public HibernateTemplate getHibernateTemplate() {
if(hibernatetemplate == null){
@SuppressWarnings("unused")
HibernateTemplate hibernatetemplate = new HibernateTemplate(this.sessionFactory);
}
return hibernatetemplate;
}

/**
* @param sessionfactory the sessionfactory to set
*/


public void deleteUser(User user) {
getHibernateTemplate().delete(user);
}



/**
* @param sessionFactory the sessionFactory to set
*/
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}

@SuppressWarnings("unchecked")
public List<User> findAllUser(){
return getHibernateTemplate().find("From User");
}

public void saveUser(User user) {
getHibernateTemplate().saveOrUpdate(user);
}

public void updateUser(User user) {
getHibernateTemplate().save(user);
}

}


运行错误Exception in thread "main" java.lang.NullPointerException
at com.yiyi.shop.DAO.impl.UserDaoImpl.saveUser(UserDaoImpl.java:54)
at UnitTest.main(UnitTest.java:17)




------解决方案--------------------
让UserDaoImpl继续HibernateDaoSupport 可以不用自己写getHibernateTemplate方法

------解决方案--------------------
getHibernateTemplate()为null吧?你debug看看。。。

public class UserDaoImpl extends HibernateDaoSupport implements UserDao {
....
}

extends一下试试