休止状態を使用しているプログラムが終了しない 質問する

休止状態を使用しているプログラムが終了しない 質問する

Hibernateを使用してプログラムを作成しました。

プログラムは実行中であるにもかかわらず、メイン関数の終了に達します。

SessionFactoryHibernate バージョン 4.x を使用して構成されている場合に発生するかどうかが疑問です。

設定方法が間違っていますか?


マニュアル1_1_first_hibernate_apps.java

public static void main(String[] args) {

    args[0] ="list";
    if (args.length <= 0) {
        System.err.println("argement was not given");
        return;
    }

    manual1_1_first_hibernate_apps mgr = new manual1_1_first_hibernate_apps();

    if (args[0].equals("store")) {
        mgr.createAndStoreEvent("My Event", new Date());
    }
    else if (args[0].equals("list")) {
        mgr.<Event>listEvents().stream()
            .map(e -> "Event: " + e.getTitle() + " Time: " + e.getDate())
            .forEach(System.out::println);
    }
    Util.getSessionFactory().close();
}

private <T> List<T> listEvents() {
    Session session = Util.getSessionFactory().getCurrentSession();
    session.beginTransaction();
    List<T> events = Util.autoCast(session.createQuery("from Event").list());
    session.getTransaction().commit();
    return events;
}

ユーティリティ

private static final SessionFactory sessionFactory;

/**
 * build a SessionFactory
 */
static {
    try {
        // Create the SessionFactory from hibernate.cfg.xml

        // hibernate version lower than 4.x are as follows
        // # it successful termination. but buildSessionFactory method is deprecated.
        // sessionFactory = new Configuration().configure().buildSessionFactory();

        // version 4.3 and later
        // # it does not terminate. I manually terminated.
        Configuration configuration = new Configuration().configure();
        StandardServiceRegistry serviceRegistry = 
                new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
        sessionFactory = configuration.buildSessionFactory(serviceRegistry);
    }
    catch (Throwable ex) {
        // Make sure you log the exception, as it might be swallowed
        System.err.println("Initial SessionFactory creation failed." + ex);
        throw new ExceptionInInitializerError(ex);
    }
}

/**
 * @return built SessionFactory
 */
public static SessionFactory getSessionFactory() {
    return sessionFactory;
}

プログラムが終了し、buildSessionFactory メソッドを使用する場合の次のコンソール ログ スニペット。

2 08, 2014 8:42:25 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH000030: Cleaning up connection pool [jdbc:derby:D:\Java\jdk1.7.0_03(x86)\db\bin\testdb]

ただし、非推奨の buildSessionFactory メソッドを使用せず、終了した場合 (プログラムが実行中の場合)、上記の 2 行は表示されません。

環境:

休止状態 4.3.1
 ダービー
 1.8 の
 IntelliJ IDEA 13

ベストアンサー1

私も今日この問題に遭遇しましたが、解決策は、メイン メソッド (またはスレッド) の最後で、次のようにセッション ファクトリを閉じる必要があることがわかりました。

sessionFactory.close();

その後、プログラムは正常に終了します。

メインメソッドで JavaFX 8 を使用する場合は、以下を追加します。

@Override
public void stop() throws Exception {
    sessionFactory.close();
}

このメソッドは、セッション ファクトリを閉じ、プログラム終了時にスレッドを破棄します。

おすすめ記事