EJB實(shí)體關(guān)系

2018-12-09 15:12 更新

EJB 3.0提供了選項(xiàng)來(lái)定義數(shù)據(jù)庫(kù)實(shí)體關(guān)系/映射,比如一對(duì)一,一對(duì)多,多對(duì)一和多對(duì)多的關(guān)系。以下是相關(guān)的注解。

  • One To One 一對(duì)一 -對(duì)象是一對(duì)一的關(guān)系。例如,乘客可以在旅行時(shí)使用一張單程票。

  • One To Many 一對(duì)多 -對(duì)象是一對(duì)多關(guān)系例如,一個(gè)父親可以多個(gè)孩子。

  • Many To One 多對(duì)一 -對(duì)象是對(duì)關(guān)系。例如多個(gè)孩子,單身母親。

  • Many To Many 多對(duì)多 -對(duì)象是多對(duì)多的關(guān)系。舉例來(lái)說(shuō),一本書(shū)可以多發(fā)作者和作者可以寫(xiě)多本圖書(shū)。

我們將在這里展示使用多對(duì)多的映射。若要表示多對(duì)多關(guān)系,三個(gè)需要。

  • Book 書(shū)書(shū)表記錄的書(shū)

  • Author 作者-作者有記錄Author表 

  • BOOK_AUTHOR -具有上述書(shū)籍和作者表的鏈接表BOOK_AUTHOR。


創(chuàng)建表

BOOK_AUTHOR默認(rèn)數(shù)據(jù)庫(kù)的Postgres創(chuàng)建一個(gè)表book author。

CREATE TABLE book (
   book_id     integer,   
   name   varchar(50)      
);
CREATE TABLE author (
   author_id   integer,
   name   varchar(50)      
);
CREATE TABLE book_author (
   book_id     integer,
   author_id   integer 
);


創(chuàng)建實(shí)體類(lèi)

@Entity
@Table(name="author")
public class Author implements Serializable{
   private int id;
   private String name;
   ...   
}
@Entity
@Table(name="book")
public class Book implements Serializable{
   private int id;
   private String title;
   private Set<Author> authors;
   ...   
}


本書(shū)實(shí)體使用多對(duì)多注釋

@Entity
public class Book implements Serializable{
   ...
   @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE}
      , fetch = FetchType.EAGER)
   @JoinTable(table = @Table(name = "book_author"),
      joinColumns = {@JoinColumn(name = "book_id")},
      inverseJoinColumns = {@JoinColumn(name = "author_id")})
   public Set<Author> getAuthors()
   {
      return authors;
   }
   ...
}


示例應(yīng)用程序

我們創(chuàng)建一個(gè)測(cè)試 EJB 應(yīng)用程序來(lái)測(cè)試 EJB 3.0 實(shí)體關(guān)系對(duì)象

步驟描述
1用包com.tutorialspoint.entity下一個(gè)名字EjbComponentEJB作為解釋的創(chuàng)建項(xiàng)目-創(chuàng)建應(yīng)用程序一章。請(qǐng)使用EJB創(chuàng)建的項(xiàng)目-持久章這樣本章了解EJB概念嵌入的對(duì)象。
2包下com.tutorialspoint.entity創(chuàng)建Author.java作為EJB解釋-創(chuàng)建應(yīng)用程序一章。保持不變的文件其余部分。
3包下com.tutorialspoint.entity創(chuàng)建Book.java。使用EJB -持久章作為參考。保持不變的文件其余部分。
4清理并生成應(yīng)用程序,確保業(yè)務(wù)邏輯正在按要求。
5最后,部署JBoss應(yīng)用服務(wù)器上的jar文件的形式應(yīng)用。如果尚未啟動(dòng)JBoss應(yīng)用服務(wù)器將自動(dòng)被啟動(dòng)。
6現(xiàn)在創(chuàng)建EJB客戶(hù)端,以同樣的方式一個(gè)基于控制臺(tái)的應(yīng)用程序在EJB解釋-創(chuàng)建應(yīng)用程序一章的主題創(chuàng)建客戶(hù)機(jī)訪問(wèn)EJB。


EJBComponent(EJB模塊)

Author.java

package com.tutorialspoint.entity;

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

@Entity
@Table(name="author")
public class Author implements Serializable{
    
   private int id;
   private String name;

   public Author(){}

   public Author(int id, String name){
      this.id = id;
      this.name = name;
   }
   
   @Id  
   @GeneratedValue(strategy= GenerationType.IDENTITY)
   @Column(name="author_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;
   }

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


Book.java

package com.tutorialspoint.entity;


import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;

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

   private int id;
   private String name;
   private Set<Author> authors;

   public Book(){        
   }

   @Id  
   @GeneratedValue(strategy= GenerationType.IDENTITY)
   @Column(name="book_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;
   }

   public void setAuthors(Set<Author> authors) {
      this.authors = authors;
   }    
   
   @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE}
      , fetch = FetchType.EAGER)
   @JoinTable(table = @Table(name = "book_author"),
      joinColumns = {@JoinColumn(name = "book_id")},
      inverseJoinColumns = {@JoinColumn(name = "author_id")})
   public Set<Author> getAuthors()
   {
      return authors;
   }
}


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<Book> 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<Book> getBooks() {
      return entityManager.createQuery("From Book").getResultList();
   }
}
  • 一旦你部署EjbComponent項(xiàng)目到JBoss上,注意jboss的日志。

  • JBoss已經(jīng)自動(dòng)創(chuàng)建一個(gè)JNDI條目-  LibraryPersistentBean/remote

  • 我們將使用這個(gè)查詢(xún)字符串獲取遠(yuǎn)程業(yè)務(wù)類(lèi)型的對(duì)象- com.tutorialspoint.interceptor.LibraryPersistentBeanRemote


JBoss應(yīng)用服務(wù)器日志輸出

...
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客戶(hù)端)

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
  • 這些屬性是用來(lái)初始化java命名服務(wù)的InitialContext對(duì)象

  • InitialContext對(duì)象將用于查找無(wú)狀態(tài)會(huì)話(huà)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.*;
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 
1. Add Book
2. Exit 
Enter Choice: ");
   }
   
   private void testEmbeddedObjects(){

      try {
         int choice = 1; 

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

         while (choice != 2) {
            String bookName;
            String authorName;
            
            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 author name: ");
               authorName = brConsoleReader.readLine();               
               Book book = new Book();
               book.setName(bookName);
			   Author author = new Author();
			   author.setName(authorName);
			   Set<Author> authors = new HashSet<Author>();
			   authors.add(author);
               book.setAuthors(authors);

               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.print("Author: ");
            Author[] authors = (Author[])books.getAuthors().toArray();
            for(int j=0;j<authors.length;j++){
               System.out.println(authors[j]);
            }
            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執(zhí)行以下任務(wù)。

  •  jndi.properties 加載屬性初始化輸出對(duì)象。

  • 在testInterceptedEjb()方法中,jndi查找名稱(chēng)——“"LibraryPersistenceBean/remote”來(lái)獲取遠(yuǎn)程業(yè)務(wù)對(duì)象(無(wú)狀態(tài)stateless ejb)。

  • 然后用戶(hù)顯示庫(kù)存儲(chǔ)用戶(hù)界面和他(她)被要求輸入選擇。

  • 如果用戶(hù)輸入1,系統(tǒng)要求書(shū)名稱(chēng)并保存這本書(shū)使用無(wú)狀態(tài)會(huì)話(huà)bean用于addBook()方法。會(huì)話(huà)Bean將這本書(shū)存儲(chǔ)在數(shù)據(jù)庫(kù)中。

  • 如果用戶(hù)輸入2,系統(tǒng)檢索書(shū)籍使用無(wú)狀態(tài)會(huì)話(huà)bean getBooks()方法并退出。


運(yùn)行客戶(hù)端訪問(wèn)EJB

在項(xiàng)目資源管理器中找到EJBTester.java。右鍵單擊EJBTester類(lèi)并選擇 run file 運(yùn)行文件

驗(yàn)證Netbeans的控制臺(tái)下面的輸出。

run:
**********************
Welcome to Book Store
**********************
Options 
1. Add Book
2. Exit 
Enter Choice: 1
Enter book name: learn html5
Enter Author name: Robert
**********************
Welcome to Book Store
**********************
Options 
1. Add Book
2. Exit 
Enter Choice: 2
Book(s) entered so far: 1
1. learn html5
Author: Robert
BUILD SUCCESSFUL (total time: 21 seconds)

以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)