getHibernateTemplate NullPointerException

时间:2012-09-27 12:57:20

标签: java hibernate jdbc nullpointerexception dao

我有一个简单的应用程序来从oracle DB中检索数据:

public class userExportImpl extends HibernateDaoSupport {

    public User getUser (final String username) throws OssObjectNotFoundException, OssIllegalArgumentException
    {
       Session session = null;
       SessionFactory sessionFactory = new
            Configuration().configure().buildSessionFactory();
       session = sessionFactory.openSession();
       User user= null;
       createHibernateTemplate(sessionFactory);
       user = (User)getHibernateTemplate().execute( new HibernateCallback()
       {
          public Object doInHibernate(Session session) throws HibernateException, SQLException
          {
            User user = (User) session.get(User.class, username);

            return user;
          }
       });
    session.close();
    return user;
}}

这是我调用getUser的main():

public class userExportTool {
public static void main(String args[]){
   userExportImpl userExport = new userExportImpl();
   User user = userExport.getUser("test");
}}

这是我尝试运行它时遇到的异常:

Exception in thread "main" java.lang.NullPointerException
    at com.tektronix.userExport.userExportImpl.getUser(userExportImpl.java:40)
    at com.tektronix.userExport.uacnExportTool.main(uacnExportTool.java:17)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)

起初我认为getHibernateTemplate需要会话工厂并打开会话,所以我添加了这些,但我仍然收到nullPointerException,我不知道为什么会发生这种情况。 hibernate.cfg.xml和User.hbm.xml都存在,我已经尝试通过更简单的方法(如session.get())使用db,因此连接必须正常。 你能给我一些想法吗?

0 个答案:

没有答案