gpt4 book ai didi

java - `SessionFactory` 和 `Session` 对象可以 't work with "try-with-resource”吗?

转载 作者:行者123 更新时间:2023-11-30 07:50:32 25 4
gpt4 key购买 nike

使用hibernate时,我想看看SessionFactorySession对象是否可以与“try-with-resource”一起使用,这样我就不能忽略调用他们的 close() 方法:

try (SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession()){

session.beginTransaction();

Customer customer = new Customer();
customer.setFirstName("James");
customer.setLastName("Bond");
customer.setSsn(999998);
customer.setAddressLine1("1111 S St");
customer.setCity("London");
customer.setState("LDN");
customer.setCountry("UK");

session.save(customer);

session.getTransaction().commit();

// session.close();
// sessionFactory.close();

} catch (Exception e) {
e.printStackTrace();
}

但是我收到错误:

CustomerTest.java:12: error: incompatible types: try-with-resources not applicable to variable type
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
^
(SessionFactory cannot be converted to AutoCloseable)
CustomerTest.java:18: error: incompatible types: try-with-resources not applicable to variable type
Session session = sessionFactory.openSession()){
^
(Session cannot be converted to AutoCloseable)
2 errors

这是否意味着 SessionFactorySession 对象不能与“try-with-resource”一起使用,因为这两个类没有实现 AutoCloseable 接口(interface)?

谢谢。

最佳答案

Does it mean that SessionFactory and Session objects can't work with "try-with-resource", because the two classes don't implement AutoCloseable interface?

是的,就是这个意思。

但是,如果您查看较新版本的 Hibernate,您会发现 SessionFactorySession在那里实现 AutoCloseable 接口(interface)。

我认为更改是在 Hibernate 5 中进行的,因此升级您的 Hibernate 版本可能是一个潜在的解决方案。

关于java - `SessionFactory` 和 `Session` 对象可以 't work with "try-with-resource”吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47765415/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com