雷林鵬分享:EJB嵌入對象

  EJB 3.0中提供了選項嵌入到實體bean的Java POJO(普通Java對象)和嵌入式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中的嵌入對象。

  步驟描述

  1創建一個項目的名稱EjbComponent下一個包com.tutorialspoint.entity中所解釋的EJB -創建應用程序一章。請使用創建的項目EJB -持久性章節因此本章來了解EJB概念嵌入的對象。

  2創建Publisher.java 包下com.tutorialspoint.entity作爲解釋的EJB -創建應用程序一章。保持不變的文件其餘部分。

  3創建Book.java 包下com.tutorialspoint.entity。使用EJB -持久性章節作爲參考。保持不變的文件其餘部分。

  4清理並生成應用程序,以確保業務邏輯正在按要求。

  5最後,部署在JBoss應用服務器jar文件的形式應用。如果尚未啓動JBoss應用服務器會得到自動啓動。

  6現在創建EJB客戶端,以同樣的方式一個基於控制檯的應用程序在解釋EJB -創建應用程序一章的主題創建客戶端訪問EJB。

  Create/Alter book table

  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 Module)

  Publisher.java

  package com.tutorialspoint.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.tutorialspoint.entity;

  import com.tutorialspoint.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.tutorialspoint.stateless;

  import com.tutorialspoint.entity.Book;

  import java.util.List;

  import javax.ejb.Remote;

  @Remote

  public interface LibraryPersistentBeanRemote {

  void addBook(Book bookName);

  List getBooks();

  }

  LibraryPersistentBean.java

  package com.tutorialspoint.stateless;

  import com.tutorialspoint.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 getBooks() {

  return entityManager.createQuery("From Book").getResultList();

  }

  }

  一旦你部署EjbComponent項目在Jboss應用服務器 ,發現jboss的日誌。

  JBoss已經自動爲我們的會話bean創建一個JNDI入口 - LibraryPersistentBean/remote.

  我們將使用這個查詢字符串來獲得遠程類型的業務對象 -com.tutorialspoint.interceptor.LibraryPersistentBeanRemote

  JBoss應用服務器的日誌輸出

  ...

  16:30:01,401 INFO [JndiSessionRegistrarBase] Binding the following Entries in Global JNDI:

  LibraryPersistentBean/remote - EJB3.x Default Remote Business Interface

  LibraryPersistentBean/remote-com.tutorialspoint.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.tutorialspoint.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.tutorialspoint.interceptor.LibraryPersistentBeanRemote - EJB3.x Remote Business Interface

  ...

  EJBTester (EJB Client)

  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

  這些屬性是用來初始化InitialContext對象的Java命名服務

  InitialContext的對象將被用於查找無狀態會話bean

  EJBTester.java

  package com.tutorialspoint.test;

  import com.tutorialspoint.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 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對象。

  In testInterceptedEjb() method, jndi lookup is done with name - "LibraryPersistenceBean/remote" to obtain the remote business object (stateless ejb).

  Then user is shown a library store User Interface and he/she is asked to enter choice.

  If user enters 1, system asks for book name and saves the book using stateless session bean addBook() method. Session Bean is storing the book in database.

  If user enters 2, system retrives books using stateless session bean getBooks() method and exits.

  運行客戶端訪問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)

  (編輯:雷林鵬 來源:網絡|侵刪)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章