简体   繁体   English

为什么使用外键获取数据会向我发送错误消息?

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

I'm just trying to fetch data using a foreign key and while it does it's job correctly I'm getting a strange error and i really don't know why since i found similar code on internet and it works just fine. 我只是尝试使用外键获取数据,虽然它可以正常工作,但是却出现了一个奇怪的错误,我真的不知道为什么,因为我在互联网上找到了类似的代码,而且效果很好。

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();

    }

And it gives me this error: 它给了我这个错误:

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

You're seeing two problems here; 您在这里看到两个问题; one is the NullPointerException that's making your program crash in the first place , and then the leak detector is triggering because you call session.close() in the try block (and so if there's an exception, it gets skipped). 首先是NullPointerException ,它使程序崩溃 ,然后泄漏检测器将触发,因为您在try块中调用session.close() (因此,如果有异常,它将被跳过)。

Your lpa is probably null because there's no record with primary key 2. 您的lpa可能为null因为没有主键2的记录。

(Also note that the style you're using is obsolete; at a minimum, use JPA interfaces ( EntityManager ) with try-with-resources, and preferably use managed transactions like Spring @Transactional .) (还请注意,您使用的样式已过时;至少,将JPA接口( EntityManager )与try-with-resources一起使用,最好使用诸如Spring @Transactional类的托管事务。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM