簡體   English   中英

為什么使用外鍵獲取數據會向我發送錯誤消息?

[英]Why is using foreign key to fetch data sending me an error?

我只是嘗試使用外鍵獲取數據,雖然它可以正常工作,但是卻出現了一個奇怪的錯誤,我真的不知道為什么,因為我在互聯網上找到了類似的代碼,而且效果很好。

try {

        Laptop lpa;
        session.beginTransaction();

        Student myStudent = session.get(Student.class, 2);
        lpa = myStudent.getLaptop(); //error refers to this line of code

        System.out.println(lpa.getVrsta());

        session.getTransaction().commit();

        session.close();

    } finally {
        sf.close();

    }

它給了我這個錯誤:

ERROR: 
    Connection leak detected: there are 1 unclosed connections upon shutting down pool jdbc:mysql://....
    Exception in thread "main" java.lang.NullPointerException
    at oto_otm_mtm.Blogic.main

您在這里看到兩個問題; 首先是NullPointerException ,它使程序崩潰 ,然后泄漏檢測器將觸發,因為您在try塊中調用session.close() (因此,如果有異常,它將被跳過)。

您的lpa可能為null因為沒有主鍵2的記錄。

(還請注意,您使用的樣式已過時;至少,將JPA接口( EntityManager )與try-with-resources一起使用,最好使用諸如Spring @Transactional類的托管事務。)

暫無
暫無

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

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