简体   繁体   中英

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).

Your lpa is probably null because there's no record with primary key 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 .)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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