Hibernate.orgCommunity Documentation
Hibernate は様々な環境で動作するようにデザインされているため、非常に多くの設定要素があります。幸いなことに、 Hibernate は、公開されているパッケージの etc/
フォルダの hibernate.properties
に、ほとんどの設定要素の適切なデフォルト値が記述されています。この hibernate.properties
をクラスパスに設定し、設定要素をカスタマイズするだけです。
org.hibernate.cfg.Configuration
のインスタンスは、 Java の型と SQL データベースのマッピング情報をすべて持っています。 Configuration
は、(不変の) SessionFactory
を生成するときに使用します。複数の XML マッピングファイルを変換し、マッピング情報にします。
通常、 org.hibernate.cfg.Configuration
インスタンスは、特定の XML マッピングファイルによって直接初期化されます。もし、マッピングファイルがクラスパスに設定されている場合、次のメソッドを使ってください。 addResource()
:
Configuration cfg = new Configuration()
.addResource("Item.hbm.xml")
.addResource("Bid.hbm.xml");
代替案 (こちらのほうが良いときもあります) としてマッピングクラスを指定する方法もあります。 Hibernate に、マッピングファイルを 見つけさせてください:
Configuration cfg = new Configuration()
.addClass(org.hibernate.auction.Item.class)
.addClass(org.hibernate.auction.Bid.class);
Hibernate は、クラスパスにある以下のような名前のマッピングファイルを見つけます。 /org/hibernate/auction/Item.hbm.xml
、 /org/hibernate/auction/Bid.hbm.xml
。この方法だと、ハードコーディングされたファイル名を排除できます。
org.hibernate.cfg.Configuration
は、設定プロパティを指定することもできます:
Configuration cfg = new Configuration()
.addClass(org.hibernate.auction.Item.class)
.addClass(org.hibernate.auction.Bid.class)
.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLInnoDBDialect")
.setProperty("hibernate.connection.datasource", "java:comp/env/jdbc/test")
.setProperty("hibernate.order_updates", "true");
Hibernate に設定プロパティを渡す方法は1つではありません。さまざまなオプションを用意しています:
java.util.Properties
インスタンスを Configuration.setProperties()
に渡します。
hibernate.properties
をクラスパスのルートディレクトリに置きます。
System
プロパティが java -Dproperty=value
を使うように設定します。
<property>
要素を hibernate.cfg.xml
(後述)に設定します。
If you want to get started quicklyhibernate.properties
is the easiest approach.
org.hibernate.cfg.Configuration
は、起動時にだけあるオブジェクトであり、一度 SessionFactory
を生成した後は、破棄されることを意図しています。
When all mappings have been parsed by the org.hibernate.cfg.Configuration
, the application must obtain a factory for org.hibernate.Session
instances. This factory is intended to be shared by all application threads:
SessionFactory sessions = cfg.buildSessionFactory();
Hibernate does allow your application to instantiate more than one org.hibernate.SessionFactory
. This is useful if you are using more than one database.
通常、開発者は org.hibernate.SessionFactory
を生成し、 SessionFactory で JDBC コネクションをプーリングしたいと考えます。そのアプローチを採用する場合、単純に org.hibernate.Session
をオープンしてください:
Session session = sessions.openSession(); // open a new Session
これだけで、プーリングした JDBC コネクションを使って目的のデータベースにアクセスすることができます。
そのためには、 JDBC コネクションのプロパティを Hibernate に設定する必要があります。すべての Hibernate プロパティ名とセマンティクスは org.hibernate.cfg.Environment
クラスに定義されています。この設定は JDBC コネクション設定の中で一番重要なものです。
もし、以下のプロパティを設定すると、 Hibernate はコネクションを取得するために(プールも) java.sql.DriverManager
を使います:
表3.1 Hibernate JDBC プロパティ
プロパティ名 | 意味 |
---|---|
hibernate.connection.driver_class | JDBC driver class |
hibernate.connection.url | JDBC URL |
hibernate.connection.username | データベースのユーザー |
hibernate.connection.password | データベースユーザーパスワード |
hibernate.connection.pool_size | maximum number of pooled connections |
Hibernate のコネクションプールアルゴリズムは非常に初歩的なものです。これはすぐに始められるようにと用意されたもので、 製品として使用することを意図していません 。また、パフォーマンスのテストのためのものでもありません。最高のパフォーマンスと安定性を持ったプールを実現したければ、サードパーティのツールをお勧めします。 hibernate.connection.pool_size
プロパティと適切なコネクションプールの設定を置き換えてください。これにより Hibernate のインターナルプールを無効にします。例えば次のように C3P0 を使います。
C3P0 はオープンソース JDBC コネクションプールで、 Hibernate の lib
ディレクトリにあります。もし、 hibernate.c3p0.*
プロパティをセットすれば、 Hibernate は、 C3P0ConnectionProvider
を使います。もし Proxool を使いたい場合は、 hibernate.properties
パッケージを参照したり、 Hibernate の Web サイトでより多くの情報を取得してください。
C3P0 用の hibernate.properties
ファイルを例として示します:
hibernate.connection.driver_class = org.postgresql.Driver hibernate.connection.url = jdbc:postgresql://localhost/mydatabase hibernate.connection.username = myuser hibernate.connection.password = secret hibernate.c3p0.min_size=5 hibernate.c3p0.max_size=20 hibernate.c3p0.timeout=1800 hibernate.c3p0.max_statements=50 hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
アプリケーションサーバー上で使う場合は、 Hibernate を設定し、アプリケーションサーバーからコネクションを取得するようにしてください。 javax.sql.Datasource
を JNDI に登録します。そしてプロパティを以下のように設定してください:
表3.2 Hibernate データソースプロパティ
プロパティ名 | 意味 |
---|---|
hibernate.connection.datasource | データソースの JNDI 名 |
hibernate.jndi.url | JNDI プロバイダの URL (オプション) |
hibernate.jndi.class | JNDI のクラス InitialContextFactory (オプション) |
hibernate.connection.username | データベースユーザ (オプション) |
hibernate.connection.password | データベースユーザのパスワード (オプション) |
アプリケーションサーバーから提供された JNDI データソースを使う hibernate.properties
ファイルの例を示します:
hibernate.connection.datasource = java:/comp/env/jdbc/test hibernate.transaction.factory_class = \ org.hibernate.transaction.JTATransactionFactory hibernate.transaction.manager_lookup_class = \ org.hibernate.transaction.JBossTransactionManagerLookup hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
JNDI データソースから取得した JDBC コネクションは、アプリケーションサーバーのコンテナ管理トランザクションに自動的に参加します。
任意のコネクションプロパティは、追加された "hibernate.connnection
" プロパティ名によって与えられます。例えば、 charSet を設定したい場合は、 hibernate.connection.charSet を使います。
JDBC コネクションを取得する戦略を持つ独自のプラグインを定義する場合は、 org.hibernate.connection.ConnectionProvider
インターフェースを実装してください。そして、実装クラスを hibernate.connection.provider_class に設定してください。
これらのプロパティはランタイムに Hibernate の挙動を制御するものです。これらのプロパティはすべて妥当なデフォルト値があり、任意で設定します。
Some of these properties are "system-level" only. System-level properties can be set only via java -Dproperty=value
or hibernate.properties
. They cannot be set by the other techniques described above.
表3.3 Hibernate 設定プロパティ
プロパティ名 | 意味 |
---|---|
hibernate.dialect | Hibernate のクラス名 org.hibernate.dialect.Dialect が入ります。これはリレーショナルデータベースごとに最適化された SQL を生成します。 例 In most cases Hibernate will actually be able to choose the correct |
hibernate.show_sql | 発行されたすべての SQL をコンソールに出力します。これはログカテゴリの org.hibernate.SQL に debug を設定する方法の代替手段です。 例 |
hibernate.format_sql | ログとコンソールの SQL を整形して表示します。 例 |
hibernate.default_schema | 生成される SQL 文のテーブルに設定するスキーマ/テーブルスペースです。 例. |
hibernate.default_catalog | 生成される SQL 文のテーブルに設定するカタログです。 例 |
hibernate.session_factory_name | org.hibernate.SessionFactory は生成後、この名前で JNDI に自動的に登録されます。 例 |
hibernate.max_fetch_depth | 外部結合フェッチの最大深度を設定します。結合する関連は対一関連のみ(一対一、多対一)です。 0 を指定すると外部結合フェッチは無効になります。 例: 推奨する値は |
hibernate.default_batch_fetch_size | 関連フェッチのデフォルト Hibernate バッチサイズを指定します。 例: 推奨する値は |
hibernate.default_entity_mode | Sets a default mode for entity representation for all sessions opened from this SessionFactory
|
hibernate.order_updates | 項目が更新されたときに、別の SQL で主キーを更新することを強制します。この場合、同時実行可能なシステムでは、まれにデッドロックが発生する可能性があります。 例 |
hibernate.generate_statistics | 有効の場合、 Hibernate はパフォーマンスチューニングに有効な統計情報を収集します。 例 |
hibernate.use_identifier_rollback | 有効の場合、オブジェクトが削除されたときに識別子プロパティをリセットし、デフォルト値にしたものを生成します。 例 |
hibernate.use_sql_comments | 有効の場合、 SQL 内にコメントを生成します。これはデバックを容易にします。デフォルトの値は false です。 例 |
hibernate.id.new_generator_mappings | Setting is relevant when using @GeneratedValue . It indicates whether or not the new IdentifierGenerator implementations are used for javax.persistence.GenerationType.AUTO , javax.persistence.GenerationType.TABLE and javax.persistence.GenerationType.SEQUENCE . Default to false to keep backward compatibility. 例 |
We recommend all new projects which make use of to use @GeneratedValue
to also set hibernate.id.new_generator_mappings=true
as the new generators are more efficient and closer to the JPA 2 specification semantic. However they are not backward compatible with existing databases (if a sequence or a table is used for id generation).
表3.4 Hibernate JDBC とコネクションプロパティ
プロパティ名 | 意味 |
---|---|
hibernate.jdbc.fetch_size | 値が0でない場合、 JDBC フェッチサイズを決定します ( Statement.setFetchSize() を呼びます)。 |
hibernate.jdbc.batch_size | 値が0でない場合、 Hibernate が JDBC2 バッチ更新を使用します。 例: 推奨する値は |
hibernate.jdbc.batch_versioned_data | Set this property to true if your JDBC driver returns correct row counts from executeBatch() . It is usually safe to turn this option on. Hibernate will then use batched DML for automatically versioned data. Defaults to false . 例 |
hibernate.jdbc.factory_class | カスタム org.hibernate.jdbc.Batcher を選びます。ほとんどのアプリケーションに、この設定プロパティは必要ありません。 例 |
hibernate.jdbc.use_scrollable_resultset | Hibernate による JDBC2 のスクロール可能なリザルトセットの使用を有効にします。このプロパティは、ユーザーによって提供された JDBC コネクションを使用している場合のみ必要で、そうでなければ Hibernate はコネクションメタデータを使用します。 例 |
hibernate.jdbc.use_streams_for_binary | JDBC へ/から binary や serializable の書き込み/読み込みストリームを使います (システムレベルのプロパティ)。 例 |
hibernate.jdbc.use_get_generated_keys | 挿入の後に自動生成された主キーを取得するための JDBC3 PreparedStatement.getGeneratedKeys() の使用を有効にします。これは JDBC3+ ドライバと JRE1.4+ を必要とし、もし Hibernate の識別子ジェネレータに問題が発生するようなら false に設定してください。デフォルトではコネクションメタデータを使いドライバの能力を決定します。 例 |
hibernate.connection.provider_class | JDBC コネクションを Hibernate に提供する独自の ConnectionProvider のクラス名。 例 |
hibernate.connection.isolation | JDBC トランザクション分離レベルを設定します。妥当な値を調べるためには java.sql.Connection をチェックしてください。しかし使用するデータベースが、すべての分離レベルをサポートしているとは限りません。 例 |
hibernate.connection.autocommit | プールされている JDBC コネクションの自動コミットを有効にする(非推奨)。 例 |
hibernate.connection.release_mode | Hibernate がいつ JDBC コネクションをリリースするかを指定します。デフォルトではセッションが明示的にクローズまたは切断されてもコネクションは保持します。アプリケーションサーバーの JTA データソースの場合、すべての JDBC コールの後、強制的にコネクションをリリースするために after_statement を使ってください。非 JTA コネクションの場合、各トランザクションが終了したときに after_transaction を使い、コネクションをリリースしてください。 auto にすると、 JTA や CMT トランザクションの場合、 after_statement でクローズし、 JDBC トランザクションの場合、 after_transaction でクローズします。 例 This setting only affects |
hibernate.connection.<propertyName> | JDBC プロパティ <propertyName> を DriverManager.getConnection() に渡します。 |
hibernate.jndi.<propertyName> | プロパティ <propertyName> を JNDI InitialContextFactory に渡します。 |
表3.5 Hibernate キャッシュプロパティ
プロパティ名 | 意味 |
---|---|
hibernate.cache.provider_class | カスタム CacheProvider のクラス名です。 例 |
hibernate.cache.use_minimal_puts | 書き込みを最小限にするために、二次キャッシュの操作を最適化します。その代わりに、読み込みがより頻繁に発生するようになります。このセッティングはクラスタキャッシュで役に立ちます。 Hibernate3 ではクラスタキャッシュ実装用にデフォルトでは有効になっています。 例 |
hibernate.cache.use_query_cache | 特定のクエリがキャッシュ可能な場合に、クエリキャッシュを有効にします。 例 |
hibernate.cache.use_second_level_cache | 二次キャッシュを完全に無効にする場合に使います。デフォルトでは有効で、クラスの <cache> マッピングで制御します。 例 |
hibernate.cache.query_cache_factory | カスタム QueryCache インターフェースのクラス名を指定します。デフォルトでは StandardQueryCache になります。 e.g. |
hibernate.cache.region_prefix | 二次キャッシュの領域名の接頭辞です。 例 |
hibernate.cache.use_structured_entries | 二次キャッシュに格納するデータを、人が理解しやすいフォーマットにします。 例 |
hibernate.cache.default_cache_concurrency_strategy | Setting used to give the name of the default org.hibernate.annotations.CacheConcurrencyStrategy to use when either @Cacheable or @Cache is used. @Cache(strategy="..") is used to override this default. |
表3.6 Hibernate トランザクションプロパティ
プロパティ名 | 意味 |
---|---|
hibernate.transaction.factory_class | Hibernate Transaction API と一緒に使われる TransactionFactory のクラス名です。 (デフォルトでは JDBCTransactionFactory です)。 例 |
jta.UserTransaction | アプリケーションサーバーから JTA UserTransaction を取得するために JTATransactionFactory に使われる JNDI 名です。 例 |
hibernate.transaction.manager_lookup_class | TransactionManagerLookup のクラス名です。 JTA 環境において、 JVM レベルのキャッシュを有効にするときか、 hilo ジェネレータが使用されるときに必要です。 例 |
hibernate.transaction.flush_before_completion | If enabled, the session will be automatically flushed during the before completion phase of the transaction. Built-in and automatic session context management is preferred, see 「コンテキスト上のセッション」. 例 |
hibernate.transaction.auto_close_session | If enabled, the session will be automatically closed during the after completion phase of the transaction. Built-in and automatic session context management is preferred, see 「コンテキスト上のセッション」. 例 |
表3.7 その他のプロパティ
プロパティ名 | 意味 |
---|---|
hibernate.current_session_context_class | Supply a custom strategy for the scoping of the "current" Session . See 「コンテキスト上のセッション」 for more information about the built-in strategies. 例 |
hibernate.query.factory_class | HQL パーサーの実装を選択します。 例 |
hibernate.query.substitutions | HQL と SQL のトークンをマッピングします。 (例えば、トークンは関数やリテラル名です)。 例 |
hibernate.hbm2ddl.auto | SessionFactory を生成したときに、自動的にスキーマ DDL を有効にしデータベースに出力します。 create-drop の場合、 SessionFactory をクローズしたときに、データベーススキーマをドロップします。 例 |
hibernate.hbm2ddl.import_files | Comma-separated names of the optional files containing SQL DML statements executed during the File order matters, the statements of a give file are executed before the statements of the following files. These statements are only executed if the schema is created ie if e.g. |
hibernate.bytecode.use_reflection_optimizer | Enables the use of bytecode manipulation instead of runtime reflection. This is a System-level property and cannot be set in 例 |
hibernate.bytecode.provider | Both javassist or cglib can be used as byte manipulation engines; the default is e.g. |
hibernate.dialect
プロパティには、使用するデータベースの正しい org.hibernate.dialect.Dialect
のサブクラスを、必ず指定すべきです。しかし方言を指定すれば、 Hibernate は上述したプロパティのいくつかについて、より適切なデフォルト値を使います。そうすれば、それらを手作業で設定する手間が省けます。
表3.8 Hibernate SQL Dialects (hibernate.dialect
)
RDBMS | Dialect |
---|---|
DB2 | org.hibernate.dialect.DB2Dialect |
DB2 AS/400 | org.hibernate.dialect.DB2400Dialect |
DB2 OS390 | org.hibernate.dialect.DB2390Dialect |
PostgreSQL | org.hibernate.dialect.PostgreSQLDialect |
MySQL5 | org.hibernate.dialect.MySQL5Dialect |
MySQL5 with InnoDB | org.hibernate.dialect.MySQL5InnoDBDialect |
MySQL with MyISAM | org.hibernate.dialect.MySQLMyISAMDialect |
Oracle (いずれのバージョンでも) | org.hibernate.dialect.OracleDialect |
Oracle 9i | org.hibernate.dialect.Oracle9iDialect |
Oracle 10g | org.hibernate.dialect.Oracle10gDialect |
Oracle 11g | org.hibernate.dialect.Oracle10gDialect |
Sybase | org.hibernate.dialect.SybaseASE15Dialect |
Sybase Anywhere | org.hibernate.dialect.SybaseAnywhereDialect |
Microsoft SQL Server 2000 | org.hibernate.dialect.SQLServerDialect |
Microsoft SQL Server 2005 | org.hibernate.dialect.SQLServer2005Dialect |
Microsoft SQL Server 2008 | org.hibernate.dialect.SQLServer2008Dialect |
SAP DB | org.hibernate.dialect.SAPDBDialect |
Informix | org.hibernate.dialect.InformixDialect |
HypersonicSQL | org.hibernate.dialect.HSQLDialect |
H2 Database | org.hibernate.dialect.H2Dialect |
Ingres | org.hibernate.dialect.IngresDialect |
Progress | org.hibernate.dialect.ProgressDialect |
Mckoi SQL | org.hibernate.dialect.MckoiDialect |
Interbase | org.hibernate.dialect.InterbaseDialect |
Pointbase | org.hibernate.dialect.PointbaseDialect |
FrontBase | org.hibernate.dialect.FrontbaseDialect |
Firebird | org.hibernate.dialect.FirebirdDialect |
もしデータベースが ANSI か、 Oracle か Sybase スタイルの外部結合をサポートしている場合、 outer join fetching は、データベースの SQL 発行回数を節約しパフォーマンスを良くします(データベース内でより多くの処理コストが発生します)。外部結合フェッチは、多対一、一対多、多対多、一対一のオブジェクト関連でグループオブジェクトを1つの SQL で SELECT
します。
hibernate.max_fetch_depth
プロパティの値を 0
にすると外部結合フェッチを すべて 無効にすることになります。 1
やそれ以上の値を設定すると、外部結合フェッチが有効になり、一対一と多対一関連が fetch="join"
としてマッピングされます。
See 「フェッチ戦略」 for more information.
Oracle は JDBC ドライバとの間でやりとりされる byte
配列のサイズを制限します。 binary
や serializable
型の大きなインスタンスを使いたければ、 hibernate.jdbc.use_streams_for_binary
を有効にしてください。 ただし これはシステムレベルの設定だけです 。
The properties prefixed by hibernate.cache
allow you to use a process or cluster scoped second-level cache system with Hibernate. See the 「第2レベルキャッシュ」 for more information.
hibernate.query.substitutions
を使うことで、新しい Hibernate クエリトークンを定義できます。例:
hibernate.query.substitutions true=1, false=0
これはトークン true
と false
を、生成される SQL において整数リテラルに翻訳します。
hibernate.query.substitutions toLowercase=LOWER
これは SQL の LOWER
関数の名前の付け替えを可能にします。
Hibernate utilizes Simple Logging Facade for Java (SLF4J) in order to log various system events. SLF4J can direct your logging output to several logging frameworks (NOP, Simple, log4j version 1.2, JDK 1.4 logging, JCL or logback) depending on your chosen binding. In order to setup logging you will need slf4j-api.jar
in your classpath together with the jar file for your preferred binding - slf4j-log4j12.jar
in the case of Log4J. See the SLF4J documentation for more detail. To use Log4j you will also need to place a log4j.properties
file in your classpath. An example properties file is distributed with Hibernate in the src/
directory.
Hibernate のログメッセージに慣れることを強くおすすめします。 Hibernate のログは読みやすく、できる限り詳細になるように努力されています。これは必須のトラブルシューティングデバイスです。以下に重要なログのカテゴリを示します:
表3.9 Hibernate ログカテゴリ
カテゴリ | 機能 |
---|---|
org.hibernate.SQL | 実行したすべての SQL(DDL)ステートメントをロギングします。 |
org.hibernate.type | すべての JDBC パラメータをロギングします。 |
org.hibernate.tool.hbm2ddl | 実行したすべての SQL(DDL)ステートメントをロギングします。 |
org.hibernate.pretty | session に関連するすべてのエンティティ(最大20)のフラッシュ時間をロギングします。 |
org.hibernate.cache | すべてのニ次キャッシュの動作をロギングします。 |
org.hibernate.transaction | トランザクションに関連する動作をロギングします。 |
org.hibernate.jdbc | JDBC リソース取得をロギングします。 |
org.hibernate.hql.ast.AST | HQL と SQL の AST のクエリパースをロギングします。 |
org.hibernate.secure | すべての JAAS 分析をロギングします。 |
org.hibernate | すべてをロギングします。(情報が大量になりますが、トラブルシューティングには便利です) |
Hibernate でアプリケーションを作成するときは、 org.hibernate.SQL
カテゴリの debug
を常に有効にしておいたほうが良いでしょう。代替方法として、 hibernate.show_sql
プロパティを有効にする方法があります。
インターフェース net.sf.hibernate.cfg.NamingStrategy
を使うとデータベースオブジェクトとスキーマ要素のための「命名標準」を指定できます。
Java の識別子からデータベースの識別子を自動生成するためのルールや、マッピングファイルで与えた「論理的な」カラムとテーブル名から「物理的な」テーブルとカラム名を生成するためのルールを用意することができます。この機能は繰り返しの雑音(例えば TBL_
プリフィックス)を取り除き、マッピングドキュメントの冗長さを減らすことに役立ちます。 Hibernate が使うデフォルトの戦略はかなり最小限に近いものです。
マッピングを追加する前に Configuration.setNamingStrategy()
を呼ぶことで以下のように異なる戦略を指定することができます:
SessionFactory sf = new Configuration()
.setNamingStrategy(ImprovedNamingStrategy.INSTANCE)
.addFile("Item.hbm.xml")
.addFile("Bid.hbm.xml")
.buildSessionFactory();
org.hibernate.cfg.ImprovedNamingStrategy
は組み込みの戦略です。これはいくつかのアプリケーションにとって有用な開始点となるかもしれません。
You can configure the persister implementation used to persist your entities and collections:
by default, Hibernate uses persisters that make sense in a relational model and follow Java Persistence's specification
you can define a PersisterClassProvider
implementation that provides the persister class used of a given entity or collection
finally, you can override them on a per entity and collection basis in the mapping using @Persister
or its XML equivalent
The latter in the list the higher in priority.
You can pass the PersisterClassProvider
instance to the Configuration
object.
SessionFactory sf = new Configuration()
.setPersisterClassProvider(customPersisterClassProvider)
.addAnnotatedClass(Order.class)
.buildSessionFactory();
The persister class provider methods, when returning a non null persister class, override the default Hibernate persisters. The entity name or the collection role are passed to the methods. It is a nice way to centralize the overriding logic of the persisters instead of spreading them on each entity or collection mapping.
もう1つの方法は hibernate.cfg.xml
という名前のファイルで十分な設定を指定する方法です。このファイルは hibernate.properties
ファイルの代わりとなります。もし両方のファイルがあれば、プロパティが置き換えられます。
XML 設定ファイルは初期設定で CLASSPATH
の root に配置してください。これが例です:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<!-- a SessionFactory instance listed as /jndi/name -->
<session-factory
name="java:hibernate/SessionFactory">
<!-- properties -->
<property name="connection.datasource">java:/comp/env/jdbc/MyDB</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">false</property>
<property name="transaction.factory_class">
org.hibernate.transaction.JTATransactionFactory
</property>
<property name="jta.UserTransaction">java:comp/UserTransaction</property>
<!-- mapping files -->
<mapping resource="org/hibernate/auction/Item.hbm.xml"/>
<mapping resource="org/hibernate/auction/Bid.hbm.xml"/>
<!-- cache settings -->
<class-cache class="org.hibernate.auction.Item" usage="read-write"/>
<class-cache class="org.hibernate.auction.Bid" usage="read-only"/>
<collection-cache collection="org.hibernate.auction.Item.bids" usage="read-write"/>
</session-factory>
</hibernate-configuration>
見てのとおり、この方法の優位性は設定のためのマッピングファイル名を外出しにできることです。 Hibernate キャッシュをチューニングしなければならないのであれば、 hibernate.cfg.xml
はより便利です。 hibernate.properties
と hibernate.cfg.xml
の どちらかを使えることを覚えておいてください。2つは同じもので、違うところといえば XML 構文を使うことの利点だけです。
XML 設定を使うことで、 Hibernate は以下のようにシンプルになります。
SessionFactory sf = new Configuration().configure().buildSessionFactory();
違う XML 設定ファイルを使うこともできます。
SessionFactory sf = new Configuration()
.configure("catdb.cfg.xml")
.buildSessionFactory();
Hibernate は J2EE 構造と統合するポイントをサポートしています:
コンテナ管理データソース: Hibernate は JNDI が提供し、コンテナが管理する JDBC コネクションを使用できます。通常、 JTA 準拠の TransactionManager
と ResourceManager
がトランザクション管理 (CMT)、特に様々なデータソースにまたがる分散トランザクションを扱います。当然プログラムでトランザクション境界を指定できます (BMT)。あるいは、記述したコードのポータビリティを保つために、オプションの Hibernate の Transaction
API を使いたくなるかもしれません。
自動 JNDI バインディング: Hibernate は JNDI が立ち上がった後に SessionFactory
を生成します。
JTA セッションバインディング: Hibernate Session
は自動的に JTA トランザクションのスコープにバインドされます。単純に SessionFactory
を JNDI から lookup して、現在の Session
を取得します。 JTA トランザクションが完了したときに、 Hibernateが Session
をフラッシュし、クローズします。トランザクション境界は、宣言 (CMT) することも、プログラム (BMT/UserTransaction) することも可能です。
JMX デプロイメント: もし JMX が使用可能なアプリケーションサーバー(例えば JBoss AS) がある場合、 Hibernate を MBean としてデプロイすることを選べます。これは Configuration
から SessionFactory
を生成するコードを無くすことができます。コンテナは HibernateService
を起動し、サービスの依存を理想的に管理します(データソースは Hibernate やその他が起動する前に使用できるようにしなければなりません)。
環境に依存しますが、もしアプリケーションサーバーが "connection containment" の例外を出す場合、設定のオプション hibernate.connection.aggressive_release
を true にしてください。
Hibernate Session
API は、アーキテクチャ内のシステムの管轄であるあらゆるトランザクションに依存しません。もしコネクションプールの JDBC を直接使いたい場合、 JDBC API から トランザクションを呼ぶことができます。もし、 J2EE アプリケーションサーバーで動作させるなら、 Bean 管理トランザクションを使い、必要に応じて UserTransaction
を JTA API から呼ぶことになるでしょう。
2つ(それ以上)の環境で互換性のあるコードを維持するために、オプションとして根本的なシステムをラッピングする Hibernate Transaction
API を推奨します。 Hibernate 設定プロパティの hibernate.transaction.factory_class
を設定することで、ある特定の Transaction
クラスのインスタンスを持つことができます。
3つの基本的な(既にある)選択を挙げます:
org.hibernate.transaction.JDBCTransactionFactory
データベース (JDBC) トランザクションに委譲します(デフォルト)
org.hibernate.transaction.JTATransactionFactory
もし、このコンテキスト(例えば、 EJB セッション Bean メソッド)で進行中のトランザクションが存在する場合、コンテナ管理トランザクションに委譲します。そうでない場合は、新しいトランザクションが開始されており、 Bean 管理トランザクションが使われます。
org.hibernate.transaction.CMTTransactionFactory
コンテナ管理 JTA トランザクションに委譲します
自分自身のトランザクション戦略(例えば、 CORBA トランザクションサービス)を定義することもできます。
Hibernate のいくつかの機能(例えば、二次キャッシュ、 JTA によるコンテキストセッション等)は管理された環境の中の JTA TransactionManager
へのアクセスを要求します。 J2EE がひとつのメカニズムに規格化されていないので、アプリケーションサーバーにおいて、 Hibernateが TransactionManager
のリファレンスを取得する方法を明確にする必要があります。
表3.10 JTA トランザクションマネージャ
Transaction Factory | Application Server |
---|---|
org.hibernate.transaction.JBossTransactionManagerLookup | JBoss AS |
org.hibernate.transaction.WeblogicTransactionManagerLookup | Weblogic |
org.hibernate.transaction.WebSphereTransactionManagerLookup | WebSphere |
org.hibernate.transaction.WebSphereExtendedJTATransactionLookup | WebSphere 6 |
org.hibernate.transaction.OrionTransactionManagerLookup | Orion |
org.hibernate.transaction.ResinTransactionManagerLookup | Resin |
org.hibernate.transaction.JOTMTransactionManagerLookup | JOTM |
org.hibernate.transaction.JOnASTransactionManagerLookup | JOnAS |
org.hibernate.transaction.JRun4TransactionManagerLookup | JRun4 |
org.hibernate.transaction.BESTransactionManagerLookup | Borland ES |
org.hibernate.transaction.JBossTSStandaloneTransactionManagerLookup | JBoss TS used standalone (ie. outside JBoss AS and a JNDI environment generally). Known to work for org.jboss.jbossts:jbossjta:4.11.0.Final |
JNDI に登録した Hibernate SessionFactory
はファクトリのルックアップと新しい Session
の作成を簡易化します。これは JNDI に登録された Datasource
には関連せず、両方とも単に同じ登録を使うことに注意してください。
もし SessionFactory
を JNDI ネームスペースに登録したい場合、特別な名前(例えば、 java:hibernate/SessionFactory
)を hibernate.session_factory_name
プロパティに使ってください。もしこのプロパティを省略した場合、 SessionFactory
は JNDI に登録されません。(これは Tomcat のようなデフォルト実装で JNDI が読み取り専用の環境の場合は特に便利です。)
SessionFactory
を JNDI に登録するとき、 Hibernate は hibernate.jndi.url
の値を使用し、hibernate.jndi.class
をイニシャルコンテキストとして具体化します。もし何も設定しない場合は、デフォルトの InitialContext
を使用します。
cfg.buildSessionFactory()
をコール後 Hibernate は自動的に SessionFactory
を JNDI に配置します。 HibernateService
と一緒に JMX デプロイメントを使わない限り、これはこの呼び出しをアプリケーション内の何らかのスタートアップコード(もしくはユーティリティクラス) に配置しなければならないことを意味します(後で議論します)。
もし JNDI SessionFactory
を使う場合、 EJB や他のクラスは JNDI ルックアップを使って SessionFactory
を取得します。
It is recommended that you bind the SessionFactory
to JNDI in a managed environment and use a static
singleton otherwise. To shield your application code from these details, we also recommend to hide the actual lookup code for a SessionFactory
in a helper class, such as HibernateUtil.getSessionFactory()
. Note that such a class is also a convenient way to startup Hibernate—see chapter 1.
The easiest way to handle Sessions
and transactions is Hibernate's automatic "current" Session
management. For a discussion of contextual sessions see 「コンテキスト上のセッション」. Using the "jta"
session context, if there is no Hibernate Session
associated with the current JTA transaction, one will be started and associated with that JTA transaction the first time you call sessionFactory.getCurrentSession()
. The Session
s retrieved via getCurrentSession()
in the "jta"
context are set to automatically flush before the transaction completes, close after the transaction completes, and aggressively release JDBC connections after each statement. This allows the Session
s to be managed by the life cycle of the JTA transaction to which it is associated, keeping user code clean of such management concerns. Your code can either use JTA programmatically through UserTransaction
, or (recommended for portable code) use the Hibernate Transaction
API to set transaction boundaries. If you run in an EJB container, declarative transaction demarcation with CMT is preferred.
SessionFactory
を JNDI から取得するためには cfg.buildSessionFactory()
行をどこかで実行していなければなりません。あなたはこれを、 static
初期化ブロック内( HibernateUtil
のような)か managed service として Hibernate をデプロイするか、どちらかで実行できます。
JBoss AS のような JMX の機能でアプリケーションサーバーにデプロイするために org.hibernate.jmx.HibernateService
を使って、配置します。実際のデプロイメントと設定はベンダー特有です。ここで例として JBoss 4.0.x 用の jboss-service.xml
を示します。
<?xml version="1.0"?>
<server>
<mbean code="org.hibernate.jmx.HibernateService"
name="jboss.jca:service=HibernateFactory,name=HibernateFactory">
<!-- Required services -->
<depends>jboss.jca:service=RARDeployer</depends>
<depends>jboss.jca:service=LocalTxCM,name=HsqlDS</depends>
<!-- Bind the Hibernate service to JNDI -->
<attribute name="JndiName">java:/hibernate/SessionFactory</attribute>
<!-- Datasource settings -->
<attribute name="Datasource">java:HsqlDS</attribute>
<attribute name="Dialect">org.hibernate.dialect.HSQLDialect</attribute>
<!-- Transaction integration -->
<attribute name="TransactionStrategy">
org.hibernate.transaction.JTATransactionFactory</attribute>
<attribute name="TransactionManagerLookupStrategy">
org.hibernate.transaction.JBossTransactionManagerLookup</attribute>
<attribute name="FlushBeforeCompletionEnabled">true</attribute>
<attribute name="AutoCloseSessionEnabled">true</attribute>
<!-- Fetching options -->
<attribute name="MaximumFetchDepth">5</attribute>
<!-- Second-level caching -->
<attribute name="SecondLevelCacheEnabled">true</attribute>
<attribute name="CacheProviderClass">org.hibernate.cache.EhCacheProvider</attribute>
<attribute name="QueryCacheEnabled">true</attribute>
<!-- Logging -->
<attribute name="ShowSqlEnabled">true</attribute>
<!-- Mapping files -->
<attribute name="MapResources">auction/Item.hbm.xml,auction/Category.hbm.xml</attribute>
</mbean>
</server>
このファイルは META-INF
ディレクトリに配置され、 JAR ファイルを拡張した .sar
(service archive) でパッケージ化されます。同様に Hibernate パッケージも必要です。また、 Hibernate はサードパーティのライブラリも要求します。コンパイルした永続化クラスとそのマッピングファイルも同様にアーカイブ(.sarファイル)に入れます。エンタープライズ Bean (通常はセッション Bean )は自身の JAR ファイルを保持しますが、1回で(ホット)デプロイ可能なユニットのためにメインサービスアーカイブとしてこの EJB JAR ファイルを含めることができます。 JBoss AS のドキュメントに JXM サービスと EJB デプロイメントのより多くの情報があります。
製作著作 © 2004 Red Hat, Inc.