web-dev-qa-db-ja.com

hibernate.cfg.xmlの代わりにhibernate.propertiesファイルを使用する方法

Hibernateを使用してサーブレットでDBに接続しようとしていますが、セッションの構成にhibernate.cfg.xmlまたはhibernate.propertiesファイルを使用できることを読んでいます。 xmlの代わりにプロパティを使用しようとすると、動作しません。 hibernate.cfg.xmlnot foundと言っていますが、XMLファイルを使用するように言及した箇所はなく、実際にそのXMLファイルを削除しました。

私を助けてください。そして、私が何か間違ったことをしている場合は私を修正してください。

12
Salman Ahmad

私が休止状態から理解したことから、最善のことはhibernate.cfg.xmlファイルでマッピングを定義し、hibernate.propertiesで他の構成を定義することです。

構成の代替アプローチは、hibernate.cfg.xmlという名前のファイルに完全な構成を指定することです。このファイルは、hibernate.propertiesファイルの代わりとして使用できます。両方が存在する場合は、プロパティをオーバーライドできます。

hibernate.cfg.xmlは、Hibernateキャッシュを調整する必要がある場合にも便利です。 hibernate.propertiesまたはhibernate.cfg.xmlのいずれかを使用することを選択します。両方とも同等です。

詳細については、次のリンクをご覧ください。

http://docs.jboss.org/hibernate/core/3.3/reference/en/html/session-configuration.html

このコードはデフォルトでhibernate.cfg.xmlを呼び出します:

Configuration configuration = new Configuration().configure();

そして、このコードはデフォルトでhibernate.propertiesを呼び出します:

Configuration configuration = new Configuration();

それが役に立てば幸い。

9
proS

_hibernate.properties_を使用している場合は、.configure()を削除します。以下のコードは、HibernateUtilセッションファクトリの実装です。

_private static SessionFactory buildSessionFactory() {
    try {
        Configuration configuration = new Configuration();
        ServiceRegistry serviceRegistry
            = new StandardServiceRegistryBuilder()
                .applySettings(configuration.getProperties()).build();
        configuration.addAnnotatedClass(LookUpModel.class);
        return configuration
                .buildSessionFactory(serviceRegistry);
    }catch(Exception e) {
        e.printStackTrace();
        throw new RuntimeException("There is issue in hibernate util");
    }
}
_

hibernate.properitesファイル

_hibernate.connection.driver_class = com.mysql.jdbc.Driver
hibernate.connection.url = jdbc:mysql://localhost:3306/test
hibernate.connection.username = root
hibernate.connection.password = passsword
hibernate.c3p0.min_size=5
hibernate.c3p0.max_size=20
hibernate.c3p0.timeout=1800
hibernate.c3p0.max_statements=50
hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
_
2
karepu

servletからdatabaseを使用している場合、サーバーでDataSourceを定義し、すべてを定義するのではなく、1つのhibernateプロパティを指定する必要がありますおそらく現在使用している他のすべての休止状態プロパティを介して。

これには、アプリケーションとは無関係に接続プーリングおよびその他の接続関連のパラメーターを定義できるという利点があります。

たとえば、実稼働環境では、テストおよび開発環境とは異なるデータベースパスワードが使用される可能性があります。

1
Steve C