HIBERNATE - Relational Persistence for Idiomatic Java
Hibernate Reference Documentation
Hibernateレファレンスドキュメンテーション
3.2.2
Table of Contents(コンテンツテーブル)
Preface(序文)
1. Introduction to Hibernate(Hibernateの紹介)
2. Architecture(アーキテクチャ)
3. Configuration(設定)
3.1. Programmatic configuration(プログラム上の設定)
3.2. Obtaining a SessionFactory(SessionFactoryの取得)
3.4. Optional configuration properties(オプション設定プロパティ)
3.4.2. Outer Join Fetching(外部結合フェッチ)
3.4.3. Binary Streams(バイナリストリーム)
3.4.4. Second-level and query cache(2階層とクエリキャッシュ)
3.4.6. Hibernate statistics(Hibernate統計)
3.5. Logging(ロギング)
3.6. Implementing a NamingStrategy(NamingStrategyの実装)
3.8.1. Transaction strategy configuration(トランザクション戦略設定)
Chapter 3. Configuration(第3章:設定)
Because Hibernate is designed to operate in many different environments, there are a large number of configuration parameters. Fortunately, most have sensible default values and Hibernate is distributed with an example hibernate.properties file in etc/that shows the various options. Just put the example file in your classpath and customize it.
Hibernateはさまざまな環境で動作するようにデザインされているため、非常に多くの設定要素があります。幸いなことに、Hibernateは、公開されているパッケージのetc/フォルダの hibernate.propertiesに、ほとんどの設定要素の適切なデフォルト値が記述されています。この hibernate.propertiesをクラスパスに設定し、設定要素をカスタマイズするだけです。
3.1. Programmatic configuration(プログラム上の設定)
An instance of org.hibernate.cfg.Configuration represents an entire set of mappings of an application's Java types to an SQL database. The Configuration is used to build an (immutable) SessionFactory. The mappings are compiled from various XML mapping files.
org.hibernate.cfg.Configurationのインスタンスは、Javaの型とSQLデータベースのマッピング情報をすべて持っています。The Configurationは、(不変の) SessionFactoryを生成するときに使用します。複数のXMLマッピングファイルを変換し、マッピング情報にします。
You may obtain a Configuration instance by instantiating it directly and specifying XML mapping documents. If the mapping files are in the classpath, use addResource():
通常、Configurationインスタンスは、特定のXMLマッピングファイルによって直接初期化されます。もし、マッピングファイルがクラスパスに設定されている場合、addResource()メソッドを使ってください:
Configuration cfg = new Configuration()
.addResource("Item.hbm.xml")
.addResource("Bid.hbm.xml");
An alternative (sometimes better) way is to specify the mapped class, and let Hibernate find the mapping document for you:
代替案(こちらのほうが良いときもあります)としてマッピングクラスを指定する方法もあります。Hibernateに、マッピングファイルを見つけさせてください:
Configuration cfg = new Configuration()
.addClass(org.hibernate.auction.Item.class)
.addClass(org.hibernate.auction.Bid.class);
Then Hibernate will look for mapping files named/org/hibernate/auction/Item.hbm.xml and /org/hibernate/auction/Bid.hbm.xml in the classpath. This approach eliminates any hardcoded filenames.
Hibernateは、クラスパスにある以下のような名前のマッピングファイルを見つけます。/org/hibernate/auction/Item.hbm.xml、/org/hibernate/auction/Bid.hbm.xml。この方法だと、ハードコーディングされたファイル名を排除できます。
A Configuration also allows you to specify configuration properties:
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");
This is not the only way to pass configuration properties to Hibernate. The various options include:
Hibernateに設定プロパティを通す方法は1つではありません。さまざまなオプションを用意しています:
1. Pass an instance of java.util.Properties to Configuration.setProperties().
java.util.PropertiesインスタンスをConfiguration.setProperties()に渡します。
2. Place hibernate.properties in a root directory of the classpath.
hibernate.propertiesをクラスパスのルートディレクトリに置きます。
3. Set System properties using java -Dproperty=value.
Systemプロパティがjava -Dproperty=valueを使うように設定します。
4. Include <property> elements in hibernate.cfg.xml (discussed later).
property要素をhibernate.cfg.xml(後述)に設定します。
hibernate.properties is the easiest approach if you want to get started quickly.
今すぐ始めたいのなら、hibernate.propertiesを使うのが一番の近道です。
The Configuration is intended as a startup-time object, to be discarded once aSessionFactory is created.
Configurationは、起動時にだけあるオブジェクトであり、一度 SessionFactoryを生成した後は、破棄されることを意図しています。
3.2. Obtaining a SessionFactory(SessionFactoryの取得)
When all mappings have been parsed by the Configuration, the application must obtain a factory for Session instances. This factory is intended to be shared by all application threads:
Configurationがすべてのマッピング情報を解析したら、アプリケーションは、 Sessionファクトリインスタンスを取得します。このSessionFactoryは、Hibernateを使用するすべてのスレッドで共有されるべきです。
SessionFactory sessions = cfg.buildSessionFactory();
Hibernate does allow your application to instantiate more than one SessionFactory. This is useful if you are using more than one database.
Hibernateは、 SessionFactoryを複数生成することができます。これは、複数のデータベースを使用する場合に便利です。
3.3. JDBC connections(JDBC接続)
Usually, you want to have the SessionFactory create and pool JDBC connections for you. If you take this approach, opening a Session is as simple as:
通常、開発者は SessionFactoryを生成し、SessionFactoryでJDBCコネクションをプーリングしたいと考えます。そのアプローチを採用する場合、単純に Sessionをオープンしてください:
Session session = sessions.openSession(); // open a new Session
As soon as you do something that requires access to the database, a JDBC connection will be obtained from the pool.
これだけで、プーリングしたJDBCコネクションを使って目的のデータベースにアクセスすることができます。
For this to work, we need to pass some JDBC connection properties to Hibernate. All Hibernate property names and semantics are defined on the classorg.hibernate.cfg.Environment. We will now describe the most important settings for JDBC connection configuration.
そのためには、JDBCコネクションのプロパティをHibernateに設定する必要があります。すべてのHibernateプロパティ名とセマンティクスはorg.hibernate.cfg.Environmentクラスに定義されています。この設定はJDBCコネクション設定の中で一番重要なものです。
Hibernate will obtain (and pool) connections using java.sql.DriverManager if you set the following properties:
もし、以下のプロパティを設定すると、Hibernateはコネクションを取得する(プールも)ためにjava.sql.DriverManagerを使います。
Table 3.1. Hibernate JDBC Properties(HibernateJDBCプロパティ)
Property name(プロパティ名)
|
Purpose(意味)
|
hibernate.connection.driver_class
|
jdbc driver class(JDBCドライバクラス)
|
hibernate.connection.url
|
jdbc URL
|
hibernate.connection.username
|
database user(データベースユーザ)
|
hibernate.connection.password
|
database user password(データベースユーザパスワード)
|
hibernate.connection.pool_size
|
maximum number of pooled connections(プールするコネクションの最大数)
|
Hibernate's own connection pooling algorithm is however quite rudimentary. It is intended to help you get started and is not intended for use in a production system or even for performance testing. You should use a third party pool for best performance and stability. Just replace the hibernate.connection.pool_size property with connection pool specific settings. This will turn off Hibernate's internal pool. For example, you might like to use C3P0.
Hibernateのコネクションプールアルゴリズムは非常に初歩的なものです。これはすぐに始められるようにと用意されたもので、製品として使用することを意図していません。また、パフォーマンスのテストのためのものでもありません。最高のパフォーマンスと安定性を持ったプールを実現したければ、サードパーティのツールをお勧めします。hibernate.connection.pool_sizeプロパティに適切なコネクションプールサイズを記述してください。このままだとHibernateのコネクションプールを使います。例えば次のようにC3P0を使います。
C3P0 is an open source JDBC connection pool distributed along with Hibernate in the libdirectory. Hibernate will use its C3P0ConnectionProvider for connection pooling if you set hibernate.c3p0.* properties. If you'd like to use Proxool refer to the packagedhibernate.properties and the Hibernate web site for more information.
C3P0はオープンソースJDBCコネクションプールで、Hibernateの libディレクトリにあります。もし、hibernate.c3p0.*プロパティをセットすれば、Hibernateは、C3P0ConnectionProviderを使います。もしProxoolを使いたい場合は、hibernate.propertiesパッケージを参照したり、HibernateのWebサイトでより多くの情報を取得してください。
Here is an example hibernate.properties file for C3P0:
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
For use inside an application server, you should almost always configure Hibernate to obtain connections from an application server Datasource registered in JNDI. You'll need to set at least one of the following properties:
アプリケーションサーバ上で使う場合は、Hibernateを設定し、アプリケーションサーバからコネクションを取得するようにしてください。DatasourceをJNDIに登録します。そしてプロパティを以下のように設定してください。
Table 3.2. Hibernate Datasource Properties(Hibernateデータソースプロパティ)
Propery name(プロパティ名)
|
Purpose(意味)
|
hibernate.connection.datasource
|
datasource JNDI name(データベースのJNDI名)
|
hibernate.jndi.url
|
URL of the JNDI provider (optional) (JNDIプロバイダのURL)(オプション)
|
hibernate.jndi.class
|
class of the JNDI InitialContextFactory (optional)( JNDIクラス InitialContextFactory)(オプション)
|
hibernate.connection.username
|
database user (optional) (データベースユーザ) (オプション)
|
hibernate.connection.password
|
database user password (optional) (データベースユーザパスワード) (オプション)
|
Here's an example hibernate.properties file for an application server provided JNDI datasource:
アプリケーションサーバから提供された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
JDBC connections obtained from a JNDI datasource will automatically participate in the container-managed transactions of the application server.
JNDIデータソースから取得したJDBCコネクションは、アプリケーションサーバのコンテナ管理トランザクションに自動的に参加します。
Arbitrary connection properties may be given by prepending "hibernate.connnection" to the property name. For example, you may specify a charSet usinghibernate.connection.charSet.
任意のコネクションプロパティは、与えられた" hibernate.connnection"プロパティ名によって与えられます。例えば、 charSetを設定したい場合は、hibernate.connection.charSetを使います。
You may define your own plugin strategy for obtaining JDBC connections by implementing the interface org.hibernate.connection.ConnectionProvider. You may select a custom implementation by setting hibernate.connection.provider_class.
JDBCコネクションを取得する戦略を持つ独自のプラグインを定義する場合は、org.hibernate.connection.ConnectionProviderインターフェイスを実装してください。そして、実装クラスを hibernate.connection.provider_classに設定してください。
3.4. Optional configuration properties(オプション設定プロパティ)
There are a number of other properties that control the behaviour of Hibernate at runtime. All are optional and have reasonable default values.
これらのプロパティはHibernateの挙動を制御するものです。これらのプロパティはすべて妥当なデフォルト値があり、任意で設定します。
Warning: some of these properties are "system-level" only. System-level properties can be set only via java -Dproperty=value or hibernate.properties. They may not be set by the other techniques described above.
注意:これらのプロパティは"システムレベル"のみです。システムレベルプロパティはjava -Dproperty=value 、もしくはhibernate.propertiesでのみ設定可能です。それ以外の設定方法はありません。
Table 3.3. Hibernate Configuration Properties(Hibernate設定プロパティ)
Property name(プロパティ名)
|
Purpose(意味)
|
hibernate.dialect
|
The classname of a Hibernate Dialect which allows Hibernate to generate SQL optimized for a particular relational database.
Hibernate Dialectクラス名が入ります。これはリレーショナルデータベースごとに最適化されたSQLを生成します。
eg. full.classname.of.Dialect
|
hibernate.show_sql
|
Write all SQL statements to console. This is an alternative to setting the log categoryorg.hibernate.SQL to debug.
発行されたすべてのSQLをコンソールに出力します。これはログカテゴリの org.hibernate.SQLに debugを設定する方法の代替手段です。
eg. true | false
|
hibernate.format_sql
|
Pretty print the SQL in the log and console.
ログとコンソールにSQLを表示します。
eg. true | false
|
hibernate.default_schema
|
Qualify unqualified tablenames with the given schema/tablespace in generated SQL.
生成されるSQL文のテーブルに設定するスキーマ/テーブルスペースです。
eg. SCHEMA_NAME
|
hibernate.default_catalog
|
Qualify unqualified tablenames with the given catalog in generated SQL.
生成されるSQL文のテーブルに設定するカタログです。
eg. CATALOG_NAME
|
hibernate.session_factory_name
|
The SessionFactory will be automatically bound to this name in JNDI after it has been created.
SessionFactoryは生成後、この名前で自動的JNDIに登録されます。
eg. jndi/composite/name
|
hibernate.max_fetch_depth
|
Set a maximum "depth" for the outer join fetch tree for single-ended associations (one-to-one, many-to-one). A 0 disables default outer join fetching.
外部結合フェッチの最大深度を設定します。結合する関連は対一関連のみ(一対一、多対一)です。0を指定すると外部結合フェッチは無効になります。
eg. recommended values between 0 and 3 (推奨する値は0?3です。)
|
hibernate.default_batch_fetch_size
|
Set a default size for Hibernate batch fetching of associations.
関連フェッチのデフォルトバッチサイズを指定します。
eg. recommended values 4, 8, 16 (推奨する値は4,8,16です。)
|
hibernate.default_entity_mode
|
Set a default mode for entity representation for all sessions opened from this SessionFactory
SessionFactoryからセッションをオープンしたときに使用するエンティティのデフォルトモードを設定します。
dynamic-map, dom4j, pojo
|
hibernate.order_updates
|
Force Hibernate to order SQL updates by the primary key value of the items being updated. This will result in fewer transaction deadlocks in highly concurrent systems.
項目が更新されたときに、別のSQLで主キーを更新することを強制します。この場合、同時実行可能なシステムでは、まれにデッドロックが発生する可能性があります。
eg. true | false
|
hibernate.generate_statistics
|
If enabled, Hibernate will collect statistics useful for performance tuning.
有効の場合、Hibernateはパフォーマンスチューニングに有効な統計情報を収集します。
eg. true | false
|
hibernate.use_identifer_rollback
|
If enabled, generated identifier properties will be reset to default values when objects are deleted.
有効の場合、オブジェクトが削除されたときに識別子プロパティをリセットし、デフォルト値にしたものを生成します。
eg. true | false
|
hibernate.use_sql_comments
|
If turned on, Hibernate will generate comments inside the SQL, for easier debugging, defaults tofalse.
有効の場合、SQL内にコメントを生成します。これはデバックを容易にします。デフォルトの値は falseです。
eg. true | false
|
Table 3.4. Hibernate JDBC and Connection Properties
Property name(プロパティ名)
|
Purpose(意味)
|
hibernate.jdbc.fetch_size
|
A non-zero value determines the JDBC fetch size (calls Statement.setFetchSize()).
値が0でない場合、JDBCフェッチサイズを決定します( Statement.setFetchSize()を呼びます)。
|
hibernate.jdbc.batch_size
|
A non-zero value enables use of JDBC2 batch updates by Hibernate.
値が0でない場合、HibernateがJDBC2バッチ更新を使用します。
eg. recommended values between 5 and 30 (推奨する値は5?30です。)
|
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.
もしJDBCドライバが executeBatch()によって正確な行数を返す場合、このプロパティを trueにしてください(通常はこのオプションをONにします)。Hibernateは、自動バージョンデータのためバッチDMLを使います。デフォルトの値はfalseです。
eg. true | false
|
hibernate.jdbc.factory_class
|
Select a custom Batcher. Most applications will not need this configuration property.
カスタム Batcherを選びます。ほとんどのアプリケーションに、この設定は必要ありません。
eg. classname.of.Batcher
|
hibernate.jdbc.use_scrollable_resultset
|
Enables use of JDBC2 scrollable resultsets by Hibernate. This property is only necessary when using user supplied JDBC connections, Hibernate uses connection metadata otherwise.
スクロール可能なリザルトセットを、Hibernateが使用します。このプロパティは、JDBCコネクションがコネクションメタデータをサポートしていることが必須条件になります。
eg. true | false
|
hibernate.jdbc.use_streams_for_binary
|
Use streams when writing/reading binary orserializable types to/from JDBC (system-level property).
JDBCへ/から binaryや serializableの書き込み/読み込みストリームを使います(システムレベルのプロパティ)。
eg. true | false
|
hibernate.jdbc.use_get_generated_keys
|
Enable use of JDBC3PreparedStatement.getGeneratedKeys() to retrieve natively generated keys after insert. Requires JDBC3+ driver and JRE1.4+, set to false if your driver has problems with the Hibernate identifier generators. By default, tries to determine the driver capabilites using connection metadata.
挿入の後に自動生成された主キーを取得するための JDBC3 PreparedStatement.getGeneratedKeys()の使用を有効にします。これはJDBC3+ドライバとJRE1.4+を必要とし、もしHibernateの識別子ジェネレータに問題が発生するようならfalseに設定してください。デフォルトではコネクションメタデータを使いドライバの能力を決定します。
eg. true|false
|
hibernate.connection.provider_class
|
The classname of a custom ConnectionProviderwhich provides JDBC connections to Hibernate.
JDBCコネクションをHibernateに提供する独自のConnectionProviderの名前を指定します。
eg. classname.of.ConnectionProvider
|
hibernate.connection.isolation
|
Set the JDBC transaction isolation level. Checkjava.sql.Connection for meaningful values but note that most databases do not support all isolation levels.
JDBCトランザクション分離レベルを設定します。妥当な値を調べるためにはjava.sql.Connectionをチェックしてください。しかし使用するデータベースが、すべての分離レベルをサポートしているとは限りません。
eg. 1, 2, 4, 8
|
hibernate.connection.autocommit
|
Enables autocommit for JDBC pooled connections (not recommended).
プールされているJDBCコネクションの自動コミットを有効にする(非推奨)。
eg. true | false
|
hibernate.connection.release_mode
|
Specify when Hibernate should release JDBC connections. By default, a JDBC connection is held until the session is explicitly closed or disconnected. For an application server JTA datasource, you should use after_statement to aggressively release connections after every JDBC call. For a non-JTA connection, it often makes sense to release the connection at the end of each transaction, by usingafter_transaction. auto will chooseafter_statement for the JTA and CMT transaction strategies and after_transaction for the JDBC transaction strategy.
HibernateがJDBCコネクションをリリースするかを指定します。デフォルトではセッションが明示的にクローズまたは切断されてもコネクションは保持します。アプリケーションサーバのJTAデータソースの場合、すべてのJDBCコールの後、強制的にコネクションをリリースするためにafter_statementを使ってください。非JTAコネクションの場合、各トランザクションが終了したときに after_transactionを使い、コネクションをリリースしてください。autoにすると、JTAやCMTトランザクションの場合、 after_statementでクローズし、JDBCトランザクションの場合、after_transactionでクローズします。
eg. auto (default) | on_close | after_transaction| after_statement
Note that this setting only affects Sessions returned from SessionFactory.openSession. ForSessions obtained throughSessionFactory.getCurrentSession, theCurrentSessionContext implementation configured for use controls the connection release mode for those Sessions. SeeSection 2.5, "Contextual Sessions"
注意してください。この設定はSessionFactory.openSessionから取得した Sessionだけに効果があります。SessionFactory.getCurrentSessionを通じて取得したSessionでは、CurrentSessionContextの実装によって、コネクションのリリースモードを設定します。Section 2.5, "Contextual Sessions"を参照してください。
|
hibernate.connection.<propertyName>
|
Pass the JDBC property propertyName toDriverManager.getConnection().
JDBCの propertyNameプロパティを、DriverManager.getConnection()に渡します。
|
hibernate.jndi.<propertyName>
|
Pass the property propertyName to the JNDIInitialContextFactory.
propertyNameプロパティを、JNDI InitialContextFactoryに渡します。
|
Table 3.5. Hibernate Cache Properties(Hibernate キャッシュプロパティ)
Property name(プロパティ名)
|
Purpose(意味)
|
hibernate.cache.provider_class
|
The classname of a custom CacheProvider.
カスタム CacheProviderのクラス名です。
eg. classname.of.CacheProvider
|
hibernate.cache.use_minimal_puts
|
Optimize second-level cache operation to minimize writes, at the cost of more frequent reads. This setting is most useful for clustered caches and, in Hibernate3, is enabled by default for clustered cache implementations.
書き込みを最小限にするために、二次キャッシュの操作を最適化します。その代わりに、読み込みがより頻繁に発生するようになります。このセッティングはクラスタキャッシュで役に立ちます。Hibernate3ではクラスタキャッシュ実装用にデフォルトでは有効になっています。
eg. true|false
|
hibernate.cache.use_query_cache
|
Enable the query cache, individual queries still have to be set cachable.
特定のクエリがキャッシュ可能な場合に、クエリキャッシュを有効にします。
eg. true|false
|
hibernate.cache.use_second_level_cache
|
May be used to completely disable the second level cache, which is enabled by default for classes which specify a <cache> mapping.
二次キャッシュを完全に無効にする場合に使います。デフォルトでは有効で、クラスの<cache>マッピングで制御します。
eg. true|false
|
hibernate.cache.query_cache_factory
|
The classname of a custom QueryCacheinterface, defaults to the built-inStandardQueryCache.
カスタム QueryCacheインターフェイスのクラス名を指定します。デフォルトではStandardQueryCacheになります。
eg. classname.of.QueryCache
|
hibernate.cache.region_prefix
|
A prefix to use for second-level cache region names.
二次キャッシュの領域名の接頭辞です。
eg. prefix
|
hibernate.cache.use_structured_entries
|
Forces Hibernate to store data in the second-level cache in a more human-friendly format.
二次キャッシュに格納するデータを、人が理解しやすいフォーマットにします。
eg. true|false
|
Table 3.6. Hibernate Transaction Properties(Hibernate トランザクションプロパティ)
Property name(プロパティ名)
|
Purpose(意味)
|
hibernate.transaction.factory_class
|
The classname of a TransactionFactory to use with Hibernate Transaction API (defaults to JDBCTransactionFactory).
Hibernate TransactionAPIと一緒に使われる TransactionFactoryのクラス名です。(デフォルトではJDBCTransactionFactoryです)。
eg. classname.of.TransactionFactory
|
jta.UserTransaction
|
A JNDI name used byJTATransactionFactory to obtain the JTAUserTransaction from the application server.
アプリケーションサーバからJTA UserTransactionを取得するためにJTATransactionFactoryに使われるJNDI名です。
eg. jndi/composite/name
|
hibernate.transaction.manager_lookup_class
|
The classname of aTransactionManagerLookup - required when JVM-level caching is enabled or when using hilo generator in a JTA environment.
TransactionManagerLookup のクラス名です。JTA環境において、JVMレベルのキャッシュを有効にするために必要です。
eg.classname.of.TransactionManagerLookup
|
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; seeSection 2.5, "Contextual Sessions".
有効の場合、トランザクションのcompletionフェーズの前に自動的にセッションをフラッシュします。内臓の自動セッションコンテキスト管理に適しています。Section 2.5, "Contextual Sessions"を参照してください。
eg. true | false
|
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; seeSection 2.5, "Contextual Sessions".
有効の場合、トランザクションのcompletionフェーズの後にセッションを自動的にクローズします。内臓の自動セッションコンテキスト管理に適しています。Section 2.5, "Contextual Sessions"を参照してください。
eg. true | false
|
Table 3.7. Miscellaneous Properties(その他のプロパティ)
Property name(プロパティ名)
|
Purpose(意味)
|
hibernate.current_session_context_class
|
Supply a (custom) strategy for the scoping of the "current" Session. See Section 2.5, "Contextual Sessions"for more information about the built-in strategies.
「現在の」Sessionのための(カスタム)戦略を提供します。ビルトインストラテジーに関するその他の情報についてはSection 2.5, "Contextual Sessions"を参照してください。
eg. jta | thread | managed | custom.Class
|
hibernate.query.factory_class
|
Chooses the HQL parser implementation.
HQLパーサーの実装を選択します。
eg. org.hibernate.hql.ast.ASTQueryTranslatorFactoryororg.hibernate.hql.classic.ClassicQueryTranslatorFactory
|
hibernate.query.substitutions
|
Mapping from tokens in Hibernate queries to SQL tokens (tokens might be function or literal names, for example).
HQLとSQLのトークンをマッピングします。(例えば、トークンは関数やリテラル名です)。
eg. hqlLiteral=SQL_LITERAL, hqlFunction=SQLFUNC
|
hibernate.hbm2ddl.auto
|
Automatically validate or export schema DDL to the database when the SessionFactory is created. Withcreate-drop, the database schema will be dropped when the SessionFactory is closed explicitly.
SessionFactoryを生成したときに、自動的にスキーマDDLをDBに出力します。create-dropの場合、SessionFactoryをクローズしたときに、データベーススキーマをドロップします。
eg. validate | update | create | create-drop
|
hibernate.cglib.use_reflection_optimizer
|
Enables use of CGLIB instead of runtime reflection (System-level property). Reflection can sometimes be useful when troubleshooting, note that Hibernate always requires CGLIB even if you turn off the optimizer. You can not set this property inhibernate.cfg.xml.
実行時リフレクションの代わりのCGLIBの使用を有効にします(システムレベルのプロパティ)リフレクションはトラブルシューティングのときに役立つことがあります。オプティマイザをオフにしているときでさえ、Hibernateには必ずCGLIBが必要なことに注意してください。このプロパティは hibernate.cfg.xmlで設定できません。
eg. true | false
|
3.4.1. SQL Dialects(SQL方言)
You should always set the hibernate.dialect property to the correctorg.hibernate.dialect.Dialect subclass for your database. If you specify a dialect, Hibernate will use sensible defaults for some of the other properties listed above, saving you the effort of specifying them manually.
hibernate.dialectプロパティには、使用するデータベースの正しいorg.hibernate.dialect.Dialectのサブクラスを、必ず指定すべきです。しかし方言を指定すれば、Hibernateは上述したプロパティのいくつかについて、より適切なデフォルト値を使います。そうすれば、それらを手作業で設定する手間が省けます。
Table 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
|
MySQL
|
org.hibernate.dialect.MySQLDialect
|
MySQL with InnoDB
|
org.hibernate.dialect.MySQLInnoDBDialect
|
MySQL with MyISAM
|
org.hibernate.dialect.MySQLMyISAMDialect
|
Oracle (any version)
|
org.hibernate.dialect.OracleDialect
|
Oracle 9i/10g
|
org.hibernate.dialect.Oracle9Dialect
|
Sybase
|
org.hibernate.dialect.SybaseDialect
|
Sybase Anywhere
|
org.hibernate.dialect.SybaseAnywhereDialect
|
Microsoft SQL Server
|
org.hibernate.dialect.SQLServerDialect
|
SAP DB
|
org.hibernate.dialect.SAPDBDialect
|
Informix
|
org.hibernate.dialect.InformixDialect
|
HypersonicSQL
|
org.hibernate.dialect.HSQLDialect
|
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
|
3.4.2. Outer Join Fetching(外部結合フェッチ)
If your database supports ANSI, Oracle or Sybase style outer joins, outer join fetchingwill often increase performance by limiting the number of round trips to and from the database (at the cost of possibly more work performed by the database itself). Outer join fetching allows a whole graph of objects connected by many-to-one, one-to-many, many-to-many and one-to-one associations to be retrieved in a single SQL SELECT.
もしDBがANSIか、OracleかSybaseスタイルの外部結合をサポートしている場合、outer join fetchingは、DBのSQL発行回数を節約しパフォーマンスを良くします。(DB内でより多くの処理コストが発生します)外部結合フェッチは、多対一、一対多、多対多、一対一のオブジェクト関連でグループオブジェクトを1つのSQLで SELECTします。
Outer join fetching may be disabled globally by setting the propertyhibernate.max_fetch_depth to 0. A setting of 1 or higher enables outer join fetching for one-to-one and many-to-one associations which have been mapped with fetch="join".
hibernate.max_fetch_depthプロパティの値を 0にするとOuter join fetchingをすべて無効にすることになります。1やそれ以上の値を設定すると、外部結合フェッチが有効になり、一対一と多対一関連が fetch="join"としてマッピングされます。
See Section 19.1, "Fetching strategies" for more information.
詳しい情報のためSection 19.1, "Fetching strategies"をご覧下さい。
3.4.3. Binary Streams(バイナリストリーム)
Oracle limits the size of byte arrays that may be passed to/from its JDBC driver. If you wish to use large instances of binary or serializable type, you should enablehibernate.jdbc.use_streams_for_binary. This is a system-level setting only.
OracleはJDBCドライバとの間でやりとりされる byte 配列のサイズを制限します。binaryや serializable型の大きなインスタンスを使いたければ、hibernate.jdbc.use_streams_for_binaryを有効にしてください。ただし これはシステムレベルの設定だけです。
3.4.4. Second-level and query cache
The properties prefixed by hibernate.cache allow you to use a process or cluster scoped second-level cache system with Hibernate. See the Section 19.2, "The Second Level Cache" for more details.
hibernate.cacheプロパティ接頭辞はHibernateでプロセスやクラスタ二次キャッシュを使うとことを許可します。Section 19.2, "The Second Level Cache"により多くの詳細があります。
3.4.5. Query Language Substitution(クエリ言語置き換え)
You may define new Hibernate query tokens using hibernate.query.substitutions. For example:
hibernate.query.substitutionsを使うことで、新しいHibernateクエリトークンを定義できます。
hibernate.query.substitutions true=1, false=0
would cause the tokens true and false to be translated to integer literals in the generated SQL.
これはトークン trueと falseを、生成されるSQLにおいて整数リテラルに翻訳します。
hibernate.query.substitutions toLowercase=LOWER
would allow you to rename the SQL LOWER function.
これはSQLの LOWER関数の名前の付け替えを可能にします。
3.4.6. Hibernate statistics(Hibernate統計)
If you enable hibernate.generate_statistics, Hibernate will expose a number of metrics that are useful when tuning a running system via SessionFactory.getStatistics(). Hibernate can even be configured to expose these statistics via JMX. Read the Javadoc of the interfaces in org.hibernate.stats for more information.
hibernate.generate_statisticsを有効にした場合、動作しているシステムをチューニングするときに、SessionFactory.getStatistics()を経由して、Hibernateは便利な統計情報を出力します。JMXを経由して統計情報を出力することも可能です。Javadocのorg.hibernate.statsパッケージ内のインターフェイスにはより多くの情報があります。
3.5. Logging(ロギング)
Hibernate logs various events using Apache commons-logging.
HibernateはApache commons-loggingを使って、さまざまなイベントをログとして出力します。
The commons-logging service will direct output to either Apache Log4j (if you includelog4j.jar in your classpath) or JDK1.4 logging (if running under JDK1.4 or above). You may download Log4j from http://jakarta.apache.org. To use Log4j you will need to place a log4j.properties file in your classpath, an example properties file is distributed with Hibernate in the src/ directory.
commons-loggingサービスは(クラスパスに log4j.jarを含めれば)Apache Log4jに、また(JDK1.4かそれ以上で実行させれば)JDK1.4 loggingに直接出力します。Log4jは http://jakarta.apache.orgからダウンロードできます。Log4jを使うためには、クラスパスに log4j.propertiesファイルを配置する必要があります。例のプロパティファイルはHibernateと一緒に配布され、それは src/ディレクトリにあります。
We strongly recommend that you familiarize yourself with Hibernate's log messages. A lot of work has been put into making the Hibernate log as detailed as possible, without making it unreadable. It is an essential troubleshooting device. The most interesting log categories are the following:
Hibernateのログメッセージに慣れることを強くおすすめします。Hibernateのログは読みやすく、できる限り詳細になるように努力されています。これは必須のトラブルシューティングデバイスです。以下に重要なログのカテゴリを示します。
Table 3.9. Hibernate Log Categories(Hibernateログカテゴリ)
Category(カテゴリ)
|
Function(機能)
|
org.hibernate.SQL
|
Log all SQL DML statements as they are executed
実行したすべてのSQL(DDL)ステートメントをロギングします。
|
org.hibernate.type
|
Log all JDBC parameters
すべてのJDBCパラメータをロギングします。
|
org.hibernate.tool.hbm2ddl
|
Log all SQL DDL statements as they are executed
実行したすべてのSQL(DDL)ステートメントをロギングします。
|
org.hibernate.pretty
|
Log the state of all entities (max 20 entities) associated with the session at flush time
sessionに関連するすべてのエンティティ(最大20)のフラッシュ時間をロギングします。
|
org.hibernate.cache
|
Log all second-level cache activity
すべての2次キャッシュの動作をロギングします。
|
org.hibernate.transaction
|
Log transaction related activity
トランザクションに関連する動作をロギングします。
|
org.hibernate.jdbc
|
Log all JDBC resource acquisition
JDBCリソース取得をロギングします。
|
org.hibernate.hql.ast.AST
|
Log HQL and SQL ASTs during query parsing
HQLとSQLのASTのクエリーパースをロギングします。
|
org.hibernate.secure
|
Log all JAAS authorization requests
すべてのJAAS分析をロギングします。
|
org.hibernate
|
Log everything (a lot of information, but very useful for troubleshooting)
すべてをロギングします。(情報が大量になりますが、トラブルシューティングには便利です)
|
When developing applications with Hibernate, you should almost always work withdebug enabled for the category org.hibernate.SQL, or, alternatively, the propertyhibernate.show_sql enabled.
Hibernateでアプリケーションを作成するときは、org.hibernate.SQLカテゴリの debugを常に有効にしておいたほうが良いでしょう。代替方法として、hibernate.show_sqlを有効にする方法があります。
3.6. Implementing a NamingStrategy(NamingStrategyの実装)
The interface org.hibernate.cfg.NamingStrategy allows you to specify a "naming standard" for database objects and schema elements.
インターフェイス net.sf.hibernate.cfg.NamingStrategyを使うとデータベースオブジェクトとスキーマ要素のための「命名標準」を指定できます。
You may provide rules for automatically generating database identifiers from Java identifiers or for processing "logical" column and table names given in the mapping file into "physical" table and column names. This feature helps reduce the verbosity of the mapping document, eliminating repetitive noise (TBL_ prefixes, for example). The default strategy used by Hibernate is quite minimal.
Javaの識別子からデータベースの識別子を自動生成するためのルールや、マッピングファイルで与えた「論理的な」カラムとテーブル名から「物理的な」テーブルとカラム名を生成するためのルールを用意することができます。この機能は繰り返しの雑音(例えばTBL_プリフィックス)を取り除き、マッピングドキュメントの冗長さを減らすことに役立ちます。Hibernateが使うデフォルトの戦略はかなり最小限に近いものです。
You may specify a different strategy by calling Configuration.setNamingStrategy()before adding mappings:
マッピングを追加する前に Configuration.setNamingStrategy()を呼ぶことで以下のように異なる戦略を指定することができます:
SessionFactory sf = new Configuration()
.setNamingStrategy(ImprovedNamingStrategy.INSTANCE)
.addFile("Item.hbm.xml")
.addFile("Bid.hbm.xml")
.buildSessionFactory();
org.hibernate.cfg.ImprovedNamingStrategy is a built-in strategy that might be a useful starting point for some applications.
org.hibernate.cfg.ImprovedNamingStrategyは組み込みの戦略です。これはいくつかのアプリケーションにとって有用な開始点となるかもしれません。
3.7. XML configuration file(XML設定ファイル)
An alternative approach to configuration is to specify a full configuration in a file named hibernate.cfg.xml. This file can be used as a replacement for thehibernate.properties file or, if both are present, to override properties.
もう1つの方法は hibernate.cfg.xmlという名前のファイルで十分な設定を指定する方法です。このファイルは hibernate.propertiesファイルの代わりとなります。もし両方のファイルがあれば、プロパティが置き換えられます。
The XML configuration file is by default expected to be in the root o your CLASSPATH. Here is an example:
XML設定ファイルは初期設定で CLASSPATHに配置してください。これが例です:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/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>
As you can see, the advantage of this approach is the externalization of the mapping file names to configuration. The hibernate.cfg.xml is also more convenient once you have to tune the Hibernate cache. Note that is your choice to use either hibernate.properties orhibernate.cfg.xml, both is equivalent, except for the above mentioned benefits of using the XML syntax.
見てのとおり、この方法の優位性は設定のためのマッピングファイル名を外出しにできることです。Hibernateキャッシュをチューニングしなければならないのであれば、hibernate.cfg.xmlはより便利です。hibernate.propertiesと hibernate.cfg.xmlのどちらかを使えることを覚えておいてください。二つは同じもので、違うところといえばXML構文を使うことの利点だけです。
With the XML configuration, starting Hibernate is then as simple as
XML設定を使うことで、Hibernateは以下のようにシンプルになります。
SessionFactory sf = new Configuration().configure().buildSessionFactory();
You can pick a different XML configuration file using
違うXML設定ファイルを使うこともできます。
SessionFactory sf = new Configuration()
.configure("catdb.cfg.xml")
.buildSessionFactory();
3.8. J2EE Application Server integration(J2EEアプリケーションサーバと統合)
Hibernate has the following integration points for J2EE infrastructure:
HibernateはJ2EE構造と統合するポイントをサポートしています。
? Container-managed datasources: Hibernate can use JDBC connections managed by the container and provided through JNDI. Usually, a JTA compatibleTransactionManager and a ResourceManager take care of transaction management (CMT), esp. distributed transaction handling across several datasources. You may of course also demarcate transaction boundaries programatically (BMT) or you might want to use the optional Hibernate Transaction API for this to keep your code portable.
コンテナ管理データソース:HibernateはJNDIが提供し、コンテナが管理するJDBCコネクションを使用できます。通常、JTA準拠の TransactionManagerとResourceManagerがトランザクション管理(CMT)、特に様々なデータソースにまたがる分散トランザクションを扱います。当然プログラムでトランザクション境界を指定できます(BMT)。あるいは、記述したコードのポータビリティを保つために、オプションのHibernateの TransactionAPIを使いたくなるかもしれません。
? Automatic JNDI binding: Hibernate can bind its SessionFactory to JNDI after startup.
自動JNDIバインディング:HibernateはJNDIが立ち上がった後にSessionFactoryを生成します。
? JTA Session binding: The Hibernate Session may be automatically bound to the scope of JTA transactions. Simply lookup the SessionFactory from JNDI and get the current Session. Let Hibernate take care of flushing and closing the Session when your JTA transaction completes. Transaction demarcation is either declarative (CMT) or programmatic (BMT/UserTransaction).
JTAセッションバインディング:Hibernate Sessionのトランザクション境界はJTAトランザクションと同じになります。単純に SessionFactoryをJNDIからlookupして、現在のSessionを取得します。JTAトランザクションが完了したときに、Hibernateが Sessionをフラッシュし、クローズします。EJBデプロイメントディスクリプタの中に、トランザクション境界を宣言します。
? JMX deployment: If you have a JMX capable application server (e.g. JBoss AS), you can chose to deploy Hibernate as a managed MBean. This saves you the one line startup code to build your SessionFactory from a Configuration. The container will startup your HibernateService, and ideally also take care of service dependencies (Datasource has to be available before Hibernate starts, etc).
JMXデプロイ:もしJMXが使用可能なアプリケーションサーバ(例えばJBOSS)がある場合、HibernateをMBeanとしてデプロイすることを選べます。これは ConfigurationからSessionFactoryを生成するコードを無くすことができます。コンテナは HibernateServiceを起動し、サービスの依存を理想的に管理します(データソースはHibernateやその他が起動する前に使用できるようにしなければなりません)。
Depending on your environment, you might have to set the configuration optionhibernate.connection.aggressive_release to true if your application server shows "connection containment" exceptions.
環境に依存しますが、もし、アプリケーションサーバが"connection containment"の例外をスローするなら設定のオプション hibernate.connection.aggressive_releaseをtrueにしてください。
3.8.1. Transaction strategy configuration(トランザクション戦略設定)
The Hibernate Session API is independent of any transaction demarcation system in your architecture. If you let Hibernate use JDBC directly, through a connection pool, you may begin and end your transactions by calling the JDBC API. If you run in a J2EE application server, you might want to use bean-managed transactions and call the JTA API andUserTransaction when needed.
Hibernate SessionAPIは、アーキテクチャ内のシステムの管轄であるあらゆるトランザクションに依存しません。もしコネクションプールのJDBCを直接使いたい場合、JDBC APIからトランザクションを呼ぶことができます。もし、J2EEアプリケーションサーバで動作させるなら、Bean管理トランザクションを使い、必要に応じて UserTransactionをJTA APIから呼ぶことになるでしょう。
To keep your code portable between these two (and other) environments we recommend the optional Hibernate Transaction API, which wraps and hides the underlying system. You have to specify a factory class for Transaction instances by setting the Hibernate configuration property hibernate.transaction.factory_class.
2つ(それ以上)の環境で互換性のあるコードを維持するために、オプションとして根本的なシステムをラッピングするHibernate TransactionAPIを推奨します。Hibernate設定プロパティの hibernate.transaction.factory_classを設定することである特定の Transactionクラスのインスタンスを持つことができます。
There are three standard (built-in) choices:
3つの基本的な(既にある)選択を挙げます:
org.hibernate.transaction.JDBCTransactionFactory
delegates to database (JDBC) transactions (default)
データベース(JDBC)トランザクションに委譲します(デフォルト)
org.hibernate.transaction.JTATransactionFactory
delegates to container-managed transaction if an existing transaction is underway in this context (e.g. EJB session bean method), otherwise a new transaction is started and bean-managed transaction are used.
もし、このコンテキスト(例えば、EJBセッションBeanメソッド)で進行中のトランザクションが存在する、もしくは新しいトランザクションが開始されており、Bean管理トランザクションが使われている場合、コンテナ管理トランザクションに委譲します。
org.hibernate.transaction.CMTTransactionFactory
delegates to container-managed JTA transactions
コンテナ管理JTAトランザクションに委譲します。
You may also define your own transaction strategies (for a CORBA transaction service, for example).
自分自身のトランザクション戦略(例えば、CORBAトランザクションサービス)を定義することもできます。
Some features in Hibernate (i.e. the second level cache, Contextual Sessions with JTA, etc.) require access to the JTA TransactionManager in a managed environment. In an application server you have to specify how Hibernate should obtain a reference to theTransactionManager, since J2EE does not standardize a single mechanism:
Hibernateのいくつかの機能(例えば、二次キャッシュ、JTAによるコンテキストセッション 等)は管理された環境の中のJTA TransactionManagerへのアクセスを要求します。J2EEがひとつのメカニズムに規格化されていないので、アプリケーションサーバにおいて、Hibernateが TransactionManagerのリファレンスを取得する方法を明確にする必要があります。
Table 3.10. JTA TransactionManagers
Transaction Factory
|
Application Server
|
org.hibernate.transaction.JBossTransactionManagerLookup
|
JBoss
|
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
|
3.8.2. JNDI-bound SessionFactory(SessionFactoryのJNDIへの登録)
A JNDI bound Hibernate SessionFactory can simplify the lookup of the factory and the creation of new Sessions. Note that this is not related to a JNDI bound Datasource, both simply use the same registry!
JNDIに登録したHibernate SessionFactoryは単純にファクトリをルックアップし、新しいSessionを作ります。これはJNDIに登録された Datasourceには関連せず、お互いにシンプルにこれらの登録を使うことに注意してください。
If you wish to have the SessionFactory bound to a JNDI namespace, specify a name (eg.java:hibernate/SessionFactory) using the property hibernate.session_factory_name. If this property is omitted, the SessionFactory will not be bound to JNDI. (This is especially useful in environments with a read-only JNDI default implementation, e.g. Tomcat.)
もし SessionFactoryをJNDIネームスペースに登録したい場合、特別な名前(例えば、java:hibernate/SessionFactory)をhibernate.session_factory_nameプロパティに使ってくださいもしこのプロパティを省略した場合、 SessionFactoryはJNDIに登録されません。(これはTomcatのようなデフォルト実装でJNDIが読みより専用の環境の場合特に便利です。)
When binding the SessionFactory to JNDI, Hibernate will use the values ofhibernate.jndi.url, hibernate.jndi.class to instantiate an initial context. If they are not specified, the default InitialContext will be used.
SessionFactoryをJNDIに登録するとき、Hibernateはhibernate.jndi.urlの値を使用し、hibernate.jndi.classをイニシャルコンテキストとして具体化します。もし何も設定しない場合は、デフォルトの InitialContextを使用します。
Hibernate will automatically place the SessionFactory in JNDI after you callcfg.buildSessionFactory(). This means you will at least have this call in some startup code (or utility class) in your application, unless you use JMX deployment with theHibernateService (discussed later).
cfg.buildSessionFactory()をコール後Hibernateは自動的に SessionFactoryをJNDIに配置します。HibernateServiceと一緒にJMXデプロイメントを使わない限り、これはこの呼び出しをアプリケーション内の何らかのスタートアップコード(もしくはユーティリティクラス)に配置しなければならないことを意味します。(後で議論します)
If you use a JNDI SessionFactory, an EJB or any other class may obtain the SessionFactoryusing a JNDI lookup.
もしJNDI SessionFactoryを使う場合、EJBや他のクラスはJNDIルックアップを使ってSessionFactoryを取得します。
We recommend that you bind the SessionFactory to JNDI in a managend 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.
管理された環境では SessionFactoryをJNDIにバインドし、そうでなければ staticシングルトンを使うことを推奨します。こういった詳細からアプリケーションコードを保護するために、HibernateUtil.getSessionFactory()のようなヘルパークラスの中に、SessionFactoryをルックアップするコードを隠すことを推奨します。このようなヘルパークラスはHibernateを開始する便利な手段でもあります。1章を参照してください。
3.8.3. Current Session context management with JTA(JTAによる現在のセッションコンテキストマネージメント)
The easiest way to handle Sessions and transactions is Hibernates automatic "current"Session management. See the discussion of Section 2.5, "Contextual Sessions". 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 Sessions retrieved viagetCurrentSession() in "jta" context will be set to automatically flush before the transaction completes, close after the transaction completes, and aggressively release JDBC connections after each statement. This allows the Sessions to be managed by the lifecycle of the JTA transaction to which it is associated, keeping user code clean of such management concerns. Your code can either use JTA programmatically throughUserTransaction, 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.
もっとも簡単に Sessionとトランザクションを扱う方法は、Hibernateが自動的に「現在の」 Sessionを管理することです。Section 2.5, "Contextual Sessions"カレントセッションの説明を参照してください。もし 「JTA」セッションコンテキストを使った上で、現在のJTAトランザクションとHibernate Sessionが関連していない場合は、最初にsessionFactory.getCurrentSession()をコールし、JTAトランザクションとの関連付けを行ってください。「JTA」コンテキストの getCurrentSession()を通じて取得した Sessionは、トランザクションが完了する前に自動的にフラッシュし、完了した後には自動的にクローズします。また、各ステートメント後にJDBCコネクションを積極的にリリースします。これによりJTAトランザクションのライフサイクルで Sessionを管理することができ、ユーザーのコードからそのような管理をするコードを排除できます。UserTransactionを通じてJTAをプログラムで管理することができます。または、(ポータブルなコードであれば)Hibernate TransactionAPIをトランザクション境界として使うこともできます。EJBコンテナを使うときは、CMTによる宣言的トランザクション境界が好ましいです。
3.8.4. JMX deployment(JMXデプロイメント)
The line cfg.buildSessionFactory() still has to be executed somewhere to get aSessionFactory into JNDI. You can do this either in a static initializer block (like the one in HibernateUtil) or you deploy Hibernate as a managed service.
SessionFactoryをJNDIから取得するためにはcfg.buildSessionFactory()行をどこかで実行していなければなりません。あなたはこれを、static初期化ブロック内( HibernateUtilのような)かmanaged serviceとしてHibernateをデプロイするか、どちらかで実行できます。
Hibernate is distributed with org.hibernate.jmx.HibernateService for deployment on an application server with JMX capabilities, such as JBoss AS. The actual deployment and configuration is vendor specific. Here is an example jboss-service.xml for JBoss 4.0.x:
JBOSSのような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>
This file is deployed in a directory called META-INF and packaged in a JAR file with the extension .sar (service archive). You also need to package Hibernate, its required third-party libraries, your compiled persistent classes, as well as your mapping files in the same archive. Your enterprise beans (usually session beans) may be kept in their own JAR file, but you may include this EJB JAR file in the main service archive to get a single (hot-)deployable unit. Consult the JBoss AS documentation for more information about JMX service and EJB deployment.
このファイルは META-INFディレクトリに配置され、JARファイルを拡張した .sar (service archive)でパッケージ化されます。同様にHibernateパッケージも必要です。また、Hibernateはサードパーティのライブラリも要求します。コンパイルした永続化クラスとそのマッピングファイルも同にアーカイブ(.sarファイル)に入れます。エンタープライズbean(通常はセッションbean)は自身のJARファイルを保持しますが、1回で(ホット)デプロイ可能なユニットのためにメインサービスアーカイブとしてこのEJB JARファイルをインクルードすることができます。JBossアプリケーションサーバのドキュメントにJXMサービスとEJBデプロイメントのより多くの情報があります。
No comments:
Post a Comment