首页 文章

Hullnate 4和Spring 3.0.5集成的NullPointException

提问于
浏览
0

我尝试使用Hibernate 4.1.6和Spring 3.0.5创建Java程序 . 当我运行我的应用程序时抛出NULLPOINT EXCEPTION . 请帮助我的人

  • 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>
  • DataSource.xml

WEB-INF /班/配置/数据库/属性/ database.properties

  • database.properties

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

  • UserBeans.xml
<!-- User business object -->
  • UserDaoImpl .java

public class UserDaoImpl实现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);
            }
        }
    }
}

非常感谢你!!!

1 回答

  • 3

    您正在使用 new 关键字创建 UserDAO 对象 . 您应该通过加载appContext来启动spring容器,在您的情况下 SpringBeans.xml . 如果您使用 new 关键字Spring并不管理您的依赖项,因此,您的 sessionFactory 永远不会注入DAO实例 .

    这应该是你的内容 main() 而不是当前的内容 .

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

    ..打电话给你保存 .

相关问题