Java Hibernate session 没有被正确终止

标签 java oracle hibernate session

我正在为我的 Java 应用程序使用 Hibernate。

当hibernate打开连接时,JDBC瘦客户端打开一个 session ,如下所示:

enter image description here

完成 Oracle DB 的工作后,我关闭打开的 session 。 session 关闭并处于非 Activity 状态,而不是完全被杀死。我还在关闭 session 之前尝试使用 session.flush() 命令,但它再次不起作用。

我应该怎样做才能完全终止并删除这些 session ?

数据库连接并最终关闭的示例:

Session session = null;
Transaction transaction = null;

try
{
    session = DatabaseConnection.GetDatabaseSession();
    transaction = session.getTransaction();
    transaction.begin();

    /*
        Something something
    */

    transaction.commit();
}
catch (Exception exp)
{
    exp.printStackTrace();
}
finally
{
    if (session != null && session.isOpen())
    {
        session.close();
        session.flush();
    }
}

还有我的 GetDatabaseSession() 方法:

public static Session GetDatabaseSession() throws FileNotFoundException, NullModelException
{
    String connectionUrl = "jdbc:oracle:thin:@" + IPADDRESS + ":" + DBPORT + ":" + DATABASE;

    Properties properties = new Properties();
    properties.put("hibernate.dialect", "org.hibernate.dialect.OracleDialect");
    properties.put("hibernate.connection.driver_class", "oracle.jdbc.driver.OracleDriver");
    properties.put("hibernate.connection.url", connectionUrl);
    properties.put("hibernate.connection.username", USERNAME);
    properties.put("hibernate.connection.password", PASSWORD);
    properties.put("hibernate.default_schema", SCHEME);
    properties.put("hbm2ddl.auto", "update");
    properties.put("hibernate.query.substitutions", "true 0, false 1");

    return new Configuration()
            .addProperties(properties)
            .addAnnotatedClass(SOMECLASS.class)
            .buildSessionFactory(
                    new StandardServiceRegistryBuilder()
                            .applySettings(properties)
                            .build()).openSession();
}

最佳答案

看起来我必须关闭 SessionFactory 实体才能完全终止我的 Hibernate 打开的 session 。代码如下:

public static SessionFactory sessionFactory = null;

public static void KillSessionFactory()
{
    if (sessionFactory != null && sessionFactory.isOpen())
    {
        sessionFactory.close();
    }
}

解决我的问题的一个间接解决方案是创建 Signleton Hibernate SessionFactory,如下所述:Singleton Hibernate SessionFactory Example

关于Java Hibernate session 没有被正确终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57304210/

相关文章:

java - 无法发现程序中的空异常

java - 单击 imageButton 后如何将其删除?

java - MS Edge Chromium Webdriver 从 79.309.12 开始崩溃

java - 我收到以下代码的 SQL 语法错误和许多异常

sql - 更新零行然后提交?

java - 找到对集合 : OneToMany empty collections refering to same PersistentBag 的共享引用

java - hibernate 保存并使用相同的 session ,相同的事务

mysql - 为什么 Oracle 不能在 order by 子句中选择语句的真实性

sql - 与 CLOB 一起使用的类似 UTL_MATCH 的函数

java - 动态更新在 hibernate 状态下不起作用