- EJB 教程
- EJB - 主頁
- EJB - 概述
- EJB - 環境設定
- EJB - 建立應用程式
- EJB - 無狀態Bean
- EJB - 有狀態Bean
- EJB - 持久化
- EJB - 訊息驅動Bean
- EJB - 註解
- EJB - 回撥
- EJB - 定時器服務
- EJB - 依賴注入
- EJB - 攔截器
- EJB - 可嵌入物件
- EJB - Blobs/Clobs
- EJB - 事務
- EJB - 安全性
- EJB - JNDI 繫結
- EJB - 實體關係
- EJB - 訪問資料庫
- EJB - 查詢語言
- EJB - 異常處理
- EJB - Web 服務
- EJB - 打包應用程式
- EJB 有用資源
- EJB - 快速指南
- EJB - 有用資源
- EJB - 討論
EJB - 實體關係
EJB 3.0 提供了定義資料庫實體關係/對映的選項,例如一對一、一對多、多對一和多對多關係。
以下是相關的註解:
一對一 - 物件之間存在一對一的關係。例如,乘客一次只能使用一張票出行。
一對多 - 物件之間存在一對多的關係。例如,一個父親可以有多個孩子。
多對一 - 物件之間存在多對一的關係。例如,多個孩子有一個母親。
多對多 - 物件之間存在多對多的關係。例如,一本書可以有多個作者,一個作者可以寫多本書。
我們將在此演示 ManyToMany 對映的使用。為了表示多對多關係,需要以下三個表:
Book - 書籍表,包含書籍的記錄。
Author - 作者表,包含作者的記錄。
Book_Author - 書籍作者表,包含上述書籍和作者表的關聯。
建立表
在預設資料庫 postgres 中建立表 book、author、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 );
建立實體類
@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;
...
}
在 Book 實體中使用 ManyToMany 註解。
@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;
}
...
}
示例應用程式
讓我們建立一個測試 EJB 應用程式來測試 EJB 3.0 中的實體關係物件。
| 步驟 | 描述 |
|---|---|
| 1 | 在 EJB - 建立應用程式 章節中說明的包 com.tutorialspoint.entity 下建立一個名為 EjbComponent 的專案。請使用 EJB - 持久化 章節中建立的專案,以便在本節中理解 EJB 概念中的嵌入式物件。 |
| 2 | 在 EJB - 建立應用程式 章節中說明的包 com.tutorialspoint.entity 下建立 Author.java。保持其餘檔案不變。 |
| 3 | 建立 Book.java,位於包 com.tutorialspoint.entity 下。參考 EJB - 持久化 章節。保持其餘檔案不變。 |
| 4 | 清理並構建應用程式,以確保業務邏輯按要求工作。 |
| 5 | 最後,將應用程式以 jar 檔案的形式部署到 JBoss 應用伺服器上。如果 JBoss 應用伺服器尚未啟動,它將自動啟動。 |
| 6 | 現在建立 EJB 客戶端,一個基於控制檯的應用程式,其方式與 EJB - 建立應用程式 章節中主題 建立訪問 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();
}
}
一旦您在 JBOSS 上部署 EjbComponent 專案,請注意 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 客戶端)
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.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 \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 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 執行以下任務:
從 jndi.properties 載入屬性並初始化 InitialContext 物件。
在 testInterceptedEjb() 方法中,使用名稱 - "LibraryPersistenceBean/remote" 進行 jndi 查詢以獲取遠端業務物件(無狀態 EJB)。
然後向用戶顯示一個圖書館商店使用者介面,並要求他/她輸入選擇。
如果使用者輸入 1,系統會要求輸入書籍名稱並使用無狀態會話 Bean 的 addBook() 方法儲存書籍。會話 Bean 將書籍儲存在資料庫中。
如果使用者輸入 2,系統將使用無狀態會話 Bean 的 getBooks() 方法檢索書籍並退出。
執行客戶端以訪問 EJB
在專案資源管理器中找到 EJBTester.java。右鍵單擊 EJBTester 類並選擇 執行檔案。
在 Netbeans 控制檯中驗證以下輸出。
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)