Java™ Persistence
API (JPA) を使用するアプリケーションを Liberty プロファイルがサポートできるようにするには、必要な仕様レベルに応じて jpa-2.0 フィーチャーまたは jpa-2.1 フィーチャーを server.xml ファイルに追加します。また、パーシスタンス・コンテキストとパーシスタンス・ユニットを定義し、エンティティー・マネージャーとエンティティー・マネージャー・ファクトリーへのアクセスを構成することも必要です。
このタスクについて
![[8.5.5.6 以降]](../ng_v8556.gif)
Liberty プロファイルで使用可能な JPA フィーチャーは 2 つあります。
- jpa-2.0 フィーチャーにより、JPA 2.0 仕様に従って作成されたアプリケーション管理 JPA およびコンテナー管理 JPA を使用するアプリケーションがサポートされます。サポートは、コンテナー管理プログラミング・モデルをサポートする拡張機能と共に Apache OpenJPA の上に構築されています。
- jpa-2.1 フィーチャーにより、JPA 2.1 仕様に従って作成されたアプリケーション管理 JPA およびコンテナー管理 JPA を使用するアプリケーションがサポートされます。サポートは EclipseLink の上に構築されています。
手順
- jpa-2.0 または jpa-2.1 フィーチャーを server.xml ファイルに追加します。
- パーシスタンス・コンテキストとパーシスタンス・ユニットの定義を web.xml ファイルに追加します。
以下に例を示します。
<persistence-context-ref>
<persistence-context-ref-name>example/em</persistence-context-ref-name>
<persistence-unit-name>ExamplePersistenceUnit</persistence-unit-name>
</persistence-context-ref>
<persistence-unit-ref>
<persistence-unit-ref-name>example/emf</persistence-unit-ref-name>
<persistence-unit-name>ExamplePersistenceUnit</persistence-unit-name>
</persistence-unit-ref>
- エンティティー・マネージャーへのアクセスを構成します。
以下に例を示します。
Context ctx = new InitialContext();
UserTransaction tran = (UserTransaction) ctx.lookup("java:comp/UserTransaction");
tran.begin();
EntityManager em = (EntityManager) ctx.lookup(java:comp/env/example/em");
Thing thing = new Thing();
em.persist(thing);
tran.commit();
- エンティティー・マネージャー・ファクトリーへのアクセスを構成します。
以下に例を示します。
Context ctx = new InitialContext();
EntityManagerFactory emf = (EntityManager) ctx.lookup(java:comp/env/example/emf");
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
Thing thing = new Thing();
em.persist(thing);
tx.commit();
int id = thing.getId();
em.close();