簡體   English   中英

Hibernate Java中的會話上的空指針異常

[英]Null Pointer Exception on Session in Hibernate Java

我正在創建一個簡單的應用程序,由於某種原因,我不斷收到空指針異常。 我的猜測是,這與我的session.open是否與if語句有關? 我得到的錯誤是在finally塊上,它說session.close();。

import java.util.*;
import javax.persistence.*;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class OrderTester {
    private static SessionFactory sessionFactory;
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        Session session = null;
        Transaction transaction = null;
        System.out.println("Press 1 to log in or press 2 to sign up");
        int n = scan.nextInt();

        if (n == 1) {
            Customer c = new Customer();
            // c.logIn();
        } else if (n == 2) {
            try {
                sessionFactory = HibernateUtil.getSessionFactory();
                session = sessionFactory.openSession();
                transaction = session.beginTransaction();
                Customer c = new Customer();
                Address a = new Address();
                session.save(c);
                session.save(a);

                Scanner read = new Scanner(System.in);
                System.out.println("Enter a username");
                String userName = read.next();
                c.setUsername(userName);

                System.out.println("Enter a password");
                String password = read.next();
                c.setPassword(password);

                System.out.println("Enter the street name");
                String streetName = read.next();
                a.setStreetName(streetName);

                System.out.println("Enter city");
                String city = read.next();
                a.setCity(city);

                System.out.println("Enter state");
                String state = read.next();
                a.setState(state);

                System.out.println("Enter zipcode");
                String zipcode = read.next();
                a.setZipCode(zipcode);
                read.close();

                transaction.commit();
            } catch (Exception ex) {
                transaction.rollback();
                System.out.println("Transaction is rolled back.");
            } finally {
                session.close();
                sessionFactory.close();
            }

        }

    }
}

錯誤:

Press 1 to log in or press 2 to sign up
2
Mar 05, 2016 4:51:44 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.5.Final}
Mar 05, 2016 4:51:44 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.11.Final}
Mar 05, 2016 4:51:44 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Mar 05, 2016 4:51:44 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Mar 05, 2016 4:51:44 PM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
Mar 05, 2016 4:51:44 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
Mar 05, 2016 4:51:45 PM org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity
WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
Exception in thread "main" java.lang.NullPointerException
    at Pizza.OrderTester.main(OrderTester.java:65)

該行上的NullPointerException堆棧跟蹤中沒有其他內容僅表示session為null。 據我所知,可能發生的唯一方法是session = sessionFactory.openSession(); 分配從未執行-這意味着在sessionFactory.openSession()HibernateUtil.getSessionFactory()中發生異常,該異常被finally塊中引發的更高版本的異常隱藏。

我希望,如果您在調試器中單步執行此代碼,您將看到執行流從這兩行之一跳到catch塊,然后在transaction.rollback()上命中NullPointerException (因為事務分配從未發生過)和跳轉到finally塊,在此撞上另一個NullPointerException並退出。

由於在try / catch塊之外將sessionsessionFactory都初始化為null ,所以永遠不要假設在finally子句中它們將不為null並直接調用close() 將其更改為以下內容:

} catch (Exception ex) {
   if(transaction != null) {
      try {
         transaction.rollback();
      } catch (Exception e) { // Log error }
   }
   ex.printStackTrace();
   System.out.println("Transaction is rolled back.");
} finally {
   if(session != null) {
      try {
         session.close();
      } catch (Exception e) { // Log error }
   }

   if(sessionFactory != null) {
      try {
         sessionFactory.close();
      } catch (Exception e) { // Log error }
   }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM