[英]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.