Red Hat Training

A Red Hat training course is available for Red Hat JBoss Web Server

第3章 設定と構成設定

3.1. 構成とブートストラップ

3.1.1. パッケージング

アプリケーションサーバーとスタンドアロンアプリケーション内のエンティティマネージャの設定は永続アーカイブに存在します。永続アーカイブは、META-INF フォルダにある persistence.xml ファイルを定義する JAR ファイルです。アーカイブに含まれる適切にアノテートされたすべてのクラス (@Entity アノテーションを持ちます)、アーカイブに含まれるアノテートされたすべてのパッケージ、および Hibernate hbm.xml ファイルが永続ユニット設定に追加されます。したがって、デフォルトでは、persistence.xml が最低要件になります。
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
   version="1.0">
   <persistence-unit name="sample">
      <jta-data-source>java:/DefaultDS</jta-data-source>
      <properties>
         <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
         <property name="hibernate.hbm2ddl.auto" value="create-drop"/>
      </properties>
   </persistence-unit>
</persistence>
以下に persistence.xml ファイルの完全な例を示します。
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
   version="1.0">
   <persistence-unit name="manager1" transaction-type="JTA">
      <provider>org.hibernate.ejb.HibernatePersistence</provider>
      <jta-data-source>java:/DefaultDS</jta-data-source>
      <mapping-file>ormap.xml</mapping-file>
      <jar-file>MyApp.jar</jar-file>
      <class>org.acme.Employee</class>
      <class>org.acme.Person</class>
      <class>org.acme.Address</class>
      <properties>
         <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
         <property name="hibernate.hbm2ddl.auto" value="create-drop"/>
      </properties>
   </persistence-unit>
</persistence>
name
(属性) 各エンティティマネージャは名前を持つ必要があります。
transaction-type
(属性) 使用されたトランザクションタイプ。JTA または RESOURCE_LOCAL (デフォルトで JavaEE 環境の JTA、JavaSE 環境の RESOURCE_LOCAL に設定されます) のいずれかになります。jta-datasource が使用された場合、デフォルト値は JTA になり、non-jta-datasource が使用された場合は RESOURCE_LOCAL が使用されます。
provider
プロバイダは JPA Persistence プロバイダの完全修飾クラス名です。複数の JPA 実装を使用しない場合は、これを定義する必要はありません。これは、EJB Persistence の複数のベンダー実装を使用する場合に必要です。
jta-data-sourcenon-jta-data-source
これは、javax.sql.DataSource が存在する場所の JNDI 名です。JNDI 対応 Datasource なしで実行する場合は、JDBC 接続を Hibernate 固有のプロパティで指定する必要があります (以下参照)。
mapping-file
クラスエレメントは、マップする JPA 準拠の XML マッピングファイルを指定します。このファイルは classpath に含まれる必要があります。EJB3 仕様ごとに、Hibernate EntityManager は META_INF/orm.xml で指定された jar ファイルにあるマッピングファイルをロードしようとします。当然、明示的なマッピングファイルもロードされます。実際には、マッピングファイルエレメントの任意の XML ファイルを提供できます (hbm ファイルまたは JPA 配備記述子のいずれか)。
jar-file
jar-file エレメントは分析する jar を指定します。適切にアノテートされたすべてのクラス、アノテートされたパッケージ、およびこの jar ファイルに含まれるすべての hbm.xml ファイルが、永続ユニット設定に追加されます。このエレメントは主に Java EE 環境で使用されます。Java SE でのこれの使用は移植不可と見なされます。この場合は、絶対 url が必要です。または、ディレクトリを参照できます (これは、テスト環境で特に役に立ちます。persistence.xml ファイルはドメインモデルと同じルートディレクトリまたは jar に存在しません)。
        <jar-file>file:/home/turin/work/local/lab8/build/classes</jar-file>
exclude-unlisted-classes
アノテートされたクラスに対して主な jar ファイルをチェックしないでください。明示的なクラスだけが永続ユニットの一部となります。
class
クラスエレメントはマップする完全修飾クラス名を指定します。デフォルトでは、適切にアノテートされたすべてのクラスとアーカイブ内にあるすべての hbm.xml ファイルが永続ユニット設定に追加されます。ただし、クラスエレメントを使用して一部の外部エンティティを追加できます。仕様の拡張として、パッケージ名を <class> エレメント (<class>org.hibernate.eg</class> など) に追加できます。<class> エレメントでパッケージを指定すると、アノテートされたクラスのみが含まれます。
properties
ベンダー固有プロパティを指定するには、プロパティエレメントが使用されます。プロパティエレメントでは、Hibernate 固有の設定を定義します。また、JDBC 接続情報も指定する必要があります。
JPA 仕様ではスキーマ検証が必要になるため、persistence エレメントの文法定義を定義してください。systemId が persistence_1_0.xsd で終わる場合、Hibernate entityManager は hibernate-entitymanager.jar に組み込まれたバージョンを使用します。インターネットアクセスは実行されません。
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
   version="1.0">

3.1.2. ブートストラップ

JPA 仕様は EntityManagerFactoryEntityManager にアクセスするブートストラップ手順を定義します。ブートストラップクラスは javax.persistence.Persistence などです。
EntityManagerFactory emf = Persistence.createEntityManagerFactory("manager1");
//or
Map configOverrides = new HashMap();
configOverrides.put("hibernate.hbm2ddl.auto", "create-drop");
EntityManagerFactory programmaticEmf =
    Persistence.createEntityManagerFactory("manager1", configOverrides);
最初のバージョンはマップが空白な 2 つ目のバージョンと同等です。マップバージョンは persistence.xml ファイルで定義されたすべてのプロパティよりも優先されるオーバーライドセットです。マップで使用できる JPA プロパティが2つ存在します。
  • 使用されるプロバイダクラスを定義する javax.persistence.provider
  • 使用されるトランザクションタイプを定義する javax.persistence.transactionType (JTA または RESOURCE_LOCAL のいずれか)
  • JNDI で JTA データソース名を定義する javax.persistence.jtaDataSource
  • JNDI の JTA データソース名を定義する javax.persistence.nonJtaDataSource
Persistence.createEntityManagerFactory() が呼び出されると、永続実装が ClassLoader.getResource("META-INF/persistence.xml") メソッドを使用してクラスパスを検索し、META-INF/persistence.xml ファイルを探します。実際には、Persistence クラスはクラスパスで利用可能なすべての永続プロバイダを参照し、エンティティマネージャファクトリ manager1 の作成を行うかどうかをそれぞれの永続プロバイダに尋ねます。各プロバイダから利用可能なリソースのリストから、永続実装は persistence.xml の名前がコマンドラインで指定された名前と一致するエンティティマネージャを検索します (プロバイダ element は現在の永続プロバイダに一致する必要があります)。現在の名前を持つ persistence.xml が見つからない場合や予期された永続プロバイダが見つからない場合は、PersistenceException が発生します。
Hibernate システムレベル設定以外に、Hibernate で利用可能なすべてのプロパティを persistence.xml ファイルの properties エレメントで設定できます。または、マップのオーバーライドとして、createEntityManagerFactory() に渡します。完全なリストについては、Hibernate リファレンスドキュメンテーションを参照してください。ただし、JPA プロバイダでは 2 つのプロパティだけが存在します。

表3.1 Hibernate Entity Manager 固有のプロパティ

プロパティ名定義
hibernate.ejb.classcache. <classname>キャッシュなしに対するクラス Default のクラスキャッシュ方針 [カンマキャッシュリージョン]、fully.qualified.classname に対するデフォルトのリージョンキャッシュ (hibernate.ejb.classcache.com.acme.Cat read-write または hibernate.ejb.classcache.com.acme.Cat read-write、MyRegion).
hibernate.ejb.collectioncache. <collectionrole>キャッシュなしに対するコレクションキャッシュ方針 [カンマキャッシュリージョン]、fully.qualified.classname.role に対するデフォルトのリージョンキャッシュ (hibernate.ejb.classcache.com.acme.Cat read-write または hibernate.ejb.classcache.com.acme.Cat read-write、MyRegion)。
hibernate.ejb.cfgfileHibernate を設定するために使用する XML 設定ファイル (/hibernate.cfg.xml など)。
hibernate.archive. autodetection.par アーカイブの解析中に Hibernate Entity Manager により自動検出されたエレメントを決定します (デフォルトで class,hbm に設定されます)。
hibernate.ejb. interceptorオプションの Hibernate インターセプタ。インターセプタインスタンスはすべての Session インスタンスにより共有されます。このインターセプタは org.hibernate.Interceptor を実装する必要があり、no-arg コンストラクタを持ちます。このプロパティを hibernate.ejb.interceptor.session_scoped と組み合わせることはできません。
hibernate.ejb.interceptor. session_scopedオプションの Hibernate インターセプタ。インターセプタインスタンスは該当する Session インスタンスに固有です (したがって、非スレッドセーフの場合があります)。このインターセプタは org.hibernate.Interceptor を実装し、no-arg コンストラクタを持つ必要があります。このプロパティを hibernate.ejb.interceptor と組み合わせることはできません。
hibernate.ejb.naming_strategyオプションの命名方針。使用されるデフォルトの命名方針は EJB3NamingStrategy です。また、DefaultComponentSafeNamingStrategy を使用することもできます。
hibernate.ejb.event. <eventtype>該当するイベントタイプのイベントリスナーリスト。イベントリスナーのリストはカンマで区切られた完全修飾クラス名リストです (たとえば、hibernate.ejb.event.pre-load com.acme.SecurityListener, com.acme.AuditListener)。
hibernate.ejb. use_class_enhancerデプロイメント時にアプリケーションサーバークラス拡張を使用するかどうか (デフォルトでは false に設定されます)
hibernate.ejb. discard_pc_on_closetrue の場合は、永続コンテキストが破棄されます (clear() が呼び出されたとき)。それ以外の場合は、トランザクションが完了するまで永続コンテキストが有効なままになります。すべてのオブジェクトは管理され、すべての変更はデータベースと同期されます (デフォルトでは false に設定されます。つまり、トランザクションの完了を待機します)。
同じ設定で XML <class> 宣言と hibernate.ejb.cfgfile を同時に使用できないことに注意してください (競合が発生する可能性があります)。persistence.xml に設定されたプロパティは hibernate.cfg.xml に設定されたプロパティをオーバーライドします。

注記

hibernate.transaction.factory_class をオーバーライドしないでください。Hibernate EntityManager は EntityManager タイプに応じて適切なトランザクションファクトリを自動的に設定します (JTARESOURSE_LOCAL)。Java EE 環境を使用する場合は、hibernate.transaction.manager_lookup_class を設定できます。
J2SE 環境の典型的な設定は以下のとおりです。
<persistence>
   <persistence-unit name="manager1" transaction-type="RESOURCE_LOCAL">
      <class>org.hibernate.ejb.test.Cat</class>
      <class>org.hibernate.ejb.test.Distributor</class>
      <class>org.hibernate.ejb.test.Item</class>
      <properties>
         <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
         <property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
         <property name="hibernate.connection.username" value="sa"/>
         <property name="hibernate.connection.password" value=""/>
         <property name="hibernate.connection.url" value="jdbc:hsqldb:."/>
         <property name="hibernate.max_fetch_depth" value="3"/>
       
         <!-- cache configuration -->
         <property name="hibernate.ejb.classcache.org.hibernate.ejb.test.Item" value="read-write"/>
         <property name="hibernate.ejb.collectioncache.org.hibernate.ejb.test.Item.distributors" value="read-write, RegionName"/>

         <!-- alternatively to <class> and <property> declarations, you can use a regular hibernate.cfg.xml file -->
         <!-- property name="hibernate.ejb.cfgfile" value="/org/hibernate/ejb/test/hibernate.cfg.xml"/ -->
      </properties>
   </persistence-unit>
</persistence>
プログラムによる設定を簡単にするために、Hibernate Entity Manager は商用の API を提供します。この API は Configuration API に非常に似ており、同じコンセプトを共有します (Ejb3Configuration)。この使用方法の詳細については、JavaDoc と 『Hibernate Core リファレンスガイド』 を参照してください。
Ejb3Configuration cfg = new Ejb3Configuration();
EntityManagerFactory emf = 
  cfg.addProperties( properties ) //add some properties
     .setInterceptor( myInterceptorImpl ) // set an interceptor
     .addAnnotatedClass( MyAnnotatedClass.class ) //add a class to be mapped
     .addClass( NonAnnotatedClass.class ) //add an hbm.xml file using the Hibernate convention
     .addResource( "mypath/MyOtherCLass.hbm.xml" ) //add an hbm.xml file
     .addResource( "mypath/orm.xml" ) //add an EJB3 deployment descriptor
     .configure("/mypath/hibernate.cfg.xml") //add a regular hibernate.cfg.xml
     .buildEntityManagerFactory(); //Create the entity manager factory