0

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
Rajendra arora
  • 2,186
  • 1
  • 16
  • 23
aratata
  • 1,147
  • 1
  • 6
  • 22
  • possible duplicate of https://stackoverflow.com/questions/53966566/why-is-it-sending-me-an-unclosed-connection-error-when-everything-should-be-clea – Jabongg Jan 02 '19 at 05:17
  • You are closing the session but you are not closing the established database connection. Hence the connection leak. Please close the database connection. This will resolve the issue. – Jabongg Jan 02 '19 at 05:19
  • 1
    @Jabongg Hibernate's session usually manages the JDBC connection behind the scenes. – chrylis -cautiouslyoptimistic- Jan 02 '19 at 05:21
  • Not sure about that link, I'm just following a youtube tutorial, anyway that solution doesn't work on my code. – aratata Jan 02 '19 at 05:39

1 Answers1

0

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

chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152
  • You solved the null pointer exception but i still keep on getting ERROR: Connection leak detected: there are 1 unclosed connections upon shutting down pool jdbc:mysql://... Is it because my approach is obsolete maybe? – aratata Jan 02 '19 at 05:36
  • @aratata Did you move `session.close()` into the `finally` block (or use try-with-resources)? – chrylis -cautiouslyoptimistic- Jan 02 '19 at 11:41