Ejb-embeddable-objects

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

EJB-埋め込み可能なオブジェクト

EJB 3.0は、JAVA POJO(Plain Old Java Object)をエンティティBeanに埋め込むオプションを提供し、埋め込みPOJOクラスのメソッドを使用して列名をマッピングできます。 埋め込まれるJava POJOには、@ Embeddableとして注釈を付ける必要があります。

@Embeddable
public class Publisher implements Serializable{
   private String name;
   private String address;
   ...
}

上記のクラスは、@ Embeddedアノテーションを使用して埋め込むことができます。

@Entity
public class Book implements Serializable{
   private int id;
   private String name;
   private Publisher publisher;
   ...
   @Embedded
   @AttributeOverrides({
      @AttributeOverride(name = "name",
                      column = @Column(name = "PUBLISHER")),
      @AttributeOverride(name = "address",
                      column = @Column(name = "PUBLISHER_ADDRESS"))
   })
   public Publisher getPublisher() {
      return publisher;
   }
   ...
}

応用例

テストEJBアプリケーションを作成して、EJB 3.0の埋め込みオブジェクトをテストしましょう。

Step Description
1 Create a project with a name EjbComponent under a package com.finddevguides.entity as explained in the EJB - Create Application chapter. Please use the project created in EJB - Persistence chapter as such for this chapter to understand embedded objects in EJB concepts.
2 Create Publisher.java under package com.finddevguides.entity as explained in the EJB - Create Application chapter. Keep rest of the files unchanged.
3 Create Book.java under package com.finddevguides.entity. Use EJB - Persistence chapter as reference. Keep rest of the files unchanged.
4 Clean and Build the application to make sure business logic is working as per the requirements.
5 Finally, deploy the application in the form of a jar file on JBoss Application Server. JBoss Application server will get started automatically if it is not started yet.
6 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.

ブックテーブルの作成/変更

CREATE TABLE book (
   id     integer PRIMARY KEY,
   name   varchar(50)
);
Alter table book add publisher varchar(100);
Alter table book add publisher_address varchar(200);

EJBComponent(EJBモジュール)

Publisher.java

package com.finddevguides.entity;

import java.io.Serializable;
import javax.persistence.Embeddable;

@Embeddable
public class Publisher implements Serializable{

   private String name;
   private String address;

   public Publisher() {}

   public Publisher(String name, String address) {
      this.name = name;
      this.address = address;
   }

   public String getName() {
      return name;
   }

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

   public String getAddress() {
      return address;
   }

   public void setAddress(String address) {
      this.address = address;
   }

   public String toString() {
      return name + "," + address;
   }
}

Book.java

package com.finddevguides.entity;

import com.finddevguides.callback.BookCallbackListener;
import java.io.Serializable;

import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.Embedded;
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="book")
public class Book implements Serializable{

   private int id;
   private String name;
   private Publisher publisher;

   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;
   }


   @Embedded
   @AttributeOverrides({
      @AttributeOverride(name = "name",
         column = @Column(name = "PUBLISHER")),
      @AttributeOverride(name = "address",
         column = @Column(name = "PUBLISHER_ADDRESS"))
   })
   public Publisher getPublisher() {
      return publisher;
   }

   public void setPublisher(Publisher publisher) {
      this.publisher = publisher;
   }
}

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.interceptor.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.interceptor.LibraryPersistentBeanRemote - EJB3.x Remote Business Interface
16:30:02,723 INFO  [SessionSpecContainer] Starting jboss.j2ee:jar=EjbComponent.jar,name=LibraryPersistentBean,service=EJB3
16:30:02,723 INFO  [EJBContainer] STARTED EJB: com.finddevguides.interceptor.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.interceptor.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.stateful.LibraryBeanRemote;

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.testEmbeddedObjects();
   }

   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 testEmbeddedObjects() {

      try {
         int choice = 1;

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

         while (choice != 2) {
            String bookName;
            String publisherName;
            String publisherAddress;
            showGUI();
            String strChoice = brConsoleReader.readLine();
            choice = Integer.parseInt(strChoice);
            if (choice == 1) {
               System.out.print("Enter book name: ");
               bookName = brConsoleReader.readLine();
               System.out.print("Enter publisher name: ");
               publisherName = brConsoleReader.readLine();
               System.out.print("Enter publisher address: ");
               publisherAddress = brConsoleReader.readLine();
               Book book = new Book();
               book.setName(bookName);
               book.setPublisher
              (new Publisher(publisherName,publisherAddress));

               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());
            System.out.println("Publication: "+book.getPublisher());
            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オブジェクトを初期化します。
  • testInterceptedEjb()メソッドでは、jndiルックアップが「LibraryPersistenceBean/remote」という名前で実行され、リモートビジネスオブジェクト(ステートレスEJB)が取得されます。
  • 次に、ユーザーにライブラリストアのユーザーインターフェイスが表示され、ユーザーは 選択。
  • ユーザーが1を入力すると、システムはブック名を要求し、ステートレスセッションBeanのaddBook()メソッドを使用してブックを保存します。 セッションBeanはデータベースに本を保存しています。
  • ユーザーが2を入力すると、システムはステートレスセッションBeanのgetBooks()メソッドを使用して本を取得し、終了します。

クライアントを実行して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 html5
Enter publisher name: SAMS
Enter publisher address: DELHI
**********************
Welcome to Book Store
**********************
Options
1. Add Book
2. Exit
Enter Choice: 2
Book(s) entered so far: 1
1. learn html5
Publication: SAMS,DELHI
BUILD SUCCESSFUL (total time: 21 seconds)