Ejb-persistence

提供:Dev Guides
移動先:案内検索

EJB-永続性

EJB 2.0で使用されるエンティティBeanであるEJB 3.0は、永続化メカニズムにほぼ置き換えられています。 エンティティBeanは、テーブルとのマッピングを持つ単純なPOJOです。

以下は、永続化APIの主要なアクターです-

  • エンティティ-データストアレコードを表す永続オブジェクト。 シリアル化できるのは良いことです。
  • EntityManager -永続オブジェクト(エンティティ)の追加/削除/更新/検索などのデータ操作を行う永続インターフェイス。 また、 Query インターフェイスを使用してクエリを実行するのにも役立ちます。
  • {ブランク}
  • 持続性ユニット(persistence.xml)-持続性ユニットは、持続性メカニズムのプロパティを記述します。
  • {ブランク}
  • データソース( ds.xml)*-データソースは、接続URLなどのデータストア関連のプロパティを記述します。 ユーザー名、パスワードなど

EJBの永続化メカニズムを実証するには、次のタスクを実行する必要があります-

  • *ステップ1 *-データベースにテーブルを作成します。
  • *ステップ2 *-テーブルに対応するEntityクラスを作成します。
  • *ステップ3 *-データソースと永続性ユニットを作成します。
  • *ステップ4 *-EntityManagerインスタンスを持つステートレスEJBを作成します。
  • *ステップ5 *-ステートレスEJBを更新します。 エンティティマネージャーを介してレコードを追加し、データベースからレコードを取得するメソッドを追加します。
  • *ステップ6 *-コンソールベースのアプリケーションクライアントは、ステートレスEJBにアクセスしてデータベースにデータを保持します。

テーブルを作成

デフォルトのデータベース postgres にテーブル books を作成します。

CREATE TABLE books (
   id     integer PRIMARY KEY,
   name   varchar(50)
);

エンティティクラスを作成する

//mark it entity using Entity annotation
//map table name using Table annotation
@Entity
@Table(name="books")
public class Book implements Serializable{

   private int id;
   private String name;

   public Book() {
   }

  //mark id as primary key with autogenerated value
  //map database column id with id field
   @Id
   @GeneratedValue(strategy= GenerationType.IDENTITY)
   @Column(name="id")
   public int getId() {
      return id;
   }
   ...
}

データソースと永続性ユニットの作成

データソース(jboss-ds.xml)

<?xml version = "1.0" encoding = "UTF-8"?>
<datasources>
   <local-tx-datasource>
      <jndi-name>PostgresDS</jndi-name>
      <connection-url>jdbc:postgresql://localhost:5432/postgres</connection-url>
      <driver-class>org.postgresql.driver</driver-class>
      <user-name>sa</user-name>
      <password>sa</password>
      <min-pool-size>5</min-pool-size>
      <max-pool-size>20</max-pool-size>
      <idle-timeout-minutes>5</idle-timeout-minutes>
   </local-tx-datasource>
</datasources>

永続性ユニット(persistence.xml)

<persistence version = "1.0" 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">

   <persistence-unit name = "EjbComponentPU" transaction-type = "JTA">
      <jta-data-source>java:/PostgresDS</jta-data-source>
      <exclude-unlisted-classes>false</exclude-unlisted-classes>
      <properties/>
   </persistence-unit>

   <persistence-unit name = "EjbComponentPU2" transaction-type = "JTA">
      <provider>org.hibernate.ejb.HibernatePersistence</provider>
      <jta-data-source>java:/PostgresDS</jta-data-source>
      <exclude-unlisted-classes>false</exclude-unlisted-classes>

      <properties>
         <property name="hibernate.hbm2ddl.auto" value="update"/>
      </properties>
   </persistence-unit>

</persistence>

EntityManagerインスタンスを持つステートレスEJBを作成する

@Stateless
public class LibraryPersistentBean implements LibraryPersistentBeanRemote {

  //pass persistence unit to entityManager.
   @PersistenceContext(unitName="EjbComponentPU")
   private EntityManager entityManager;

   public void addBook(Book book) {
      entityManager.persist(book);
   }

   public List<Book> getBooks() {
      return entityManager.createQuery("From Books").getResultList();
   }
   ...
}

EJBモジュールをビルドしたら、次のセクションで作成するステートレスBeanにアクセスするためのクライアントが必要です。

応用例

EJB永続性メカニズムをテストするためのテストEJBアプリケーションを作成しましょう。

Step Description
1 Create a project with a name EjbComponent under a package com.finddevguides.entity as explained in the EJB - Create Application chapter. You can also use the project created in EJB - Create Application chapter as such for this chapter to understand EJB persistence concepts.
2 Create Book.java under package com.finddevguides.entity and modify it as shown below.
3 Create LibraryPersistentBean.java and LibraryPersistentBeanRemote as explained in the EJB - Create Application chapters and modify them as shown below.
4 Create jboss-ds.xml in EjbComponent > setup *folder and persistence.xml in EjbComponent > src > conf *folder. These folders can be seen in files tab in Netbeans. Modify these files as shown above.
5 Clean and Build the application to make sure business logic is working as per the requirements.
6 Finally, deploy the application in the form of jar file on JBoss Application Server. JBoss Application server will get started automatically if it is not started yet.
7 Now create the EJB client, a console based application in the same way as explained in the EJB - Create Application chapter under topic* Create Client to access EJB*. Modify it as shown below.

EJBComponent(EJBモジュール)

Book.java

package com.finddevguides.entity;

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="books")
public class Book implements Serializable{

   private int id;
   private String name;

   public Book() {
   }

   @Id
   @GeneratedValue(strategy= GenerationType.IDENTITY)
   @Column(name="id")
   public int getId() {
      return id;
   }

   public void setId(int id) {
      this.id = id;
   }

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }
}

LibraryPersistentBeanRemote.java

package com.finddevguides.stateless;

import com.finddevguides.entity.Book;
import java.util.List;
import javax.ejb.Remote;

@Remote
public interface LibraryPersistentBeanRemote {

   void addBook(Book bookName);

   List<Book> getBooks();

}

LibraryPersistentBean.java

package com.finddevguides.stateless;

import com.finddevguides.entity.Book;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Stateless
public class LibraryPersistentBean implements LibraryPersistentBeanRemote {

   public LibraryPersistentBean() {
   }

   @PersistenceContext(unitName="EjbComponentPU")
   private EntityManager entityManager;

   public void addBook(Book book) {
      entityManager.persist(book);
   }

   public List<Book> getBooks() {
      return entityManager.createQuery("From Book").getResultList();
   }
}
  • EjbComponentプロジェクトをJBOSSにデプロイするとすぐに、jbossログに注目してください。
  • JBossは、セッションBeanのJNDIエントリ- LibraryPersistentBean/remote を自動的に作成しました。
  • このルックアップ文字列を使用して、タイプ- com.finddevguides.stateless.LibraryPersistentBeanRemote のリモートビジネスオブジェクトを取得します。

JBoss Application Serverのログ出力

...
16:30:01,401 INFO  [JndiSessionRegistrarBase] Binding the following Entries in Global JNDI:
   LibraryPersistentBean/remote - EJB3.x Default Remote Business Interface
   LibraryPersistentBean/remote-com.finddevguides.stateless.LibraryPersistentBeanRemote - EJB3.x Remote Business Interface
16:30:02,723 INFO  [SessionSpecContainer] Starting jboss.j2ee:jar=EjbComponent.jar,name=LibraryPersistentBeanRemote,service=EJB3
16:30:02,723 INFO  [EJBContainer] STARTED EJB: com.finddevguides.stateless.LibraryPersistentBeanRemote ejbName: LibraryPersistentBean
16:30:02,731 INFO  [JndiSessionRegistrarBase] Binding the following Entries in Global JNDI:

   LibraryPersistentBean/remote - EJB3.x Default Remote Business Interface
   LibraryPersistentBean/remote-com.finddevguides.stateless.LibraryPersistentBeanRemote - EJB3.x Remote Business Interface
...

EJBTester(EJBクライアント)

jndi.properties

java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
java.naming.provider.url=localhost
  • これらのプロパティは、JavaネームサービスのInitialContextオブジェクトを初期化するために使用されます。
  • InitialContextオブジェクトは、ステートレスセッションBeanのルックアップに使用されます。

EJBTester.java

package com.finddevguides.test;

import com.finddevguides.stateless.LibraryPersistentBeanRemote;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Properties;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class EJBTester {

   BufferedReader brConsoleReader = null;
   Properties props;
   InitialContext ctx;
   {
      props = new Properties();
      try {
         props.load(new FileInputStream("jndi.properties"));
      } catch (IOException ex) {
         ex.printStackTrace();
      }
      try {
         ctx = new InitialContext(props);
      } catch (NamingException ex) {
         ex.printStackTrace();
      }
      brConsoleReader =
      new BufferedReader(new InputStreamReader(System.in));
   }

   public static void main(String[] args) {

      EJBTester ejbTester = new EJBTester();

      ejbTester.testEntityEjb();
   }

   private void showGUI() {
      System.out.println("**********************");
      System.out.println("Welcome to Book Store");
      System.out.println("**********************");
      System.out.print("Options \n1. Add Book\n2. Exit \nEnter Choice: ");
   }

   private void testEntityEjb() {

      try {
         int choice = 1;

         LibraryPersistentBeanRemote libraryBean =
         LibraryPersistentBeanRemote)ctx.lookup("LibraryPersistentBean/remote");

         while (choice != 2) {
            String bookName;
            showGUI();
            String strChoice = brConsoleReader.readLine();
            choice = Integer.parseInt(strChoice);
            if (choice == 1) {
               System.out.print("Enter book name: ");
               bookName = brConsoleReader.readLine();
               Book book = new Book();
               book.setName(bookName);
               libraryBean.addBook(book);
            } else if (choice == 2) {
               break;
            }
         }

         List<Book> booksList = libraryBean.getBooks();

         System.out.println("Book(s) entered so far: " + booksList.size());
         int i = 0;
         for (Book book:booksList) {
            System.out.println((i+1)+". " + book.getName());
            i++;
         }
      } catch (Exception e) {
         System.out.println(e.getMessage());
         e.printStackTrace();
      }finally {
         try {
            if(brConsoleReader !=null) {
               brConsoleReader.close();
            }
         } catch (IOException ex) {
            System.out.println(ex.getMessage());
         }
      }
   }
}

EJBTesterは次のタスクを実行します。

  • jndi.propertiesからプロパティをロードし、InitialContextオブジェクトを初期化します。
  • testStatefulEjb()メソッドでは、jndiルックアップが名前-"LibraryStatefulSessionBean/remote"で実行され、リモートビジネスオブジェクト(ステートフルejb)が取得されます。
  • 次に、ユーザーにライブラリストアのユーザーインターフェイスが表示され、選択を入力するように求められます。
  • ユーザーが1を入力すると、システムはブック名を要求し、ステートレスセッションBeanのaddBook()メソッドを使用してブックを保存します。 セッションBeanは、EntityManager呼び出しを介してデータベースに本を保持しています。
  • ユーザーが2を入力すると、システムはステートフルセッションBeanのgetBooks()メソッドを使用して本を取得し、終了します。
  • その後、別のjndiルックアップが「LibraryStatelessSessionBean/remote」という名前で実行され、リモートビジネスオブジェクト(ステートレスEJB)が再度取得され、書籍のリストが作成されます。

クライアントを実行してEJBにアクセスする

プロジェクトエクスプローラーでEJBTester.javaを見つけます。 EJBTesterクラスを右クリックして、 run file を選択します。

Netbeansコンソールで次の出力を確認します-

run:
**********************
Welcome to Book Store
**********************
Options
1. Add Book
2. Exit
Enter Choice: 1
Enter book name: Learn Java
**********************
Welcome to Book Store
**********************
Options
1. Add Book
2. Exit
Enter Choice: 2
Book(s) entered so far: 1
1. learn java
BUILD SUCCESSFUL (total time: 15 seconds)

EJBにアクセスするためのクライアントの再実行

EJBにアクセスする前にJBossを再起動します。

プロジェクトエクスプローラーでEJBTester.javaを見つけます。 EJBTesterクラスを右クリックして、 run file を選択します。

Netbeansコンソールで次の出力を確認します。

run:
**********************
Welcome to Book Store
**********************
Options
1. Add Book
2. Exit
Enter Choice: 1
Enter book name: Learn Spring
**********************
Welcome to Book Store
**********************
Options
1. Add Book
2. Exit
Enter Choice: 2
Book(s) entered so far: 2
1. learn java
2. Learn Spring
BUILD SUCCESSFUL (total time: 15 seconds)

上記の出力は、書籍が永続ストレージに保存され、データベースから取得されることを示しています。