EJB 3.0提供了選項(xiàng)來定義數(shù)據(jù)庫實(shí)體關(guān)系/映射,比如一對一,一對多,多對一和多對多的關(guān)系。以下是相關(guān)的注解。
One To One 一對一 -對象是一對一的關(guān)系。例如,乘客可以在旅行時使用一張單程票。
One To Many 一對多 -對象是一對多的關(guān)系。例如,一個父親可以有多個孩子。
Many To One 多對一 -對象是多對一關(guān)系。例如,多個孩子,有一位單身母親。
Many To Many 多對多 -對象是多對多的關(guān)系。舉例來說,一本書可以多發(fā)作者和作者可以寫多本圖書。
我們將在這里展示使用多對多的映射。若要表示多對多關(guān)系,三個表都需要。
Book 書- 書表記錄的書
Author 作者-作者有記錄Author表
BOOK_AUTHOR -具有上述書籍和作者表的鏈接表BOOK_AUTHOR。
在BOOK_AUTHOR默認(rèn)數(shù)據(jù)庫的Postgres創(chuàng)建一個表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; ... }
在本書實(shí)體中使用多對多注釋
@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; } ... }
讓我們創(chuàng)建一個測試 EJB 應(yīng)用程序來測試 EJB 3.0 中的實(shí)體關(guān)系對象。
步驟 | 描述 |
---|---|
1 | 用包com.tutorialspoint.entity下一個名字EjbComponent在EJB作為解釋的創(chuàng)建項(xiàng)目-創(chuàng)建應(yīng)用程序一章。請使用EJB創(chuàng)建的項(xiàng)目-持久章這樣本章了解EJB概念嵌入的對象。 |
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)用。如果尚未啟動JBoss應(yīng)用服務(wù)器將自動被啟動。 |
6 | 現(xiàn)在創(chuàng)建EJB客戶端,以同樣的方式一個基于控制臺的應(yīng)用程序在EJB解釋-創(chuàng)建應(yīng)用程序一章的主題創(chuàng)建客戶機(jī)訪問EJB。 |
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; } }
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; } }
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(); }
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)自動創(chuàng)建一個JNDI條目- LibraryPersistentBean/remote。
我們將使用這個查詢字符串獲取遠(yuǎn)程業(yè)務(wù)類型的對象- com.tutorialspoint.interceptor.LibraryPersistentBeanRemote
... 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 ...
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命名服務(wù)的InitialContext對象
InitialContext對象將用于查找無狀態(tài)會話bean
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 加載屬性并初始化輸出對象。
在testInterceptedEjb()方法中,jndi查找名稱——“"LibraryPersistenceBean/remote”來獲取遠(yuǎn)程業(yè)務(wù)對象(無狀態(tài)stateless ejb)。
然后用戶顯示庫存儲用戶界面和他(她)被要求輸入選擇。
如果用戶輸入1,系統(tǒng)要求書名稱并保存這本書使用無狀態(tài)會話bean用于addBook()方法。會話Bean將這本書存儲在數(shù)據(jù)庫中。
如果用戶輸入2,系統(tǒng)檢索書籍使用無狀態(tài)會話bean getBooks()方法并退出。
在項(xiàng)目資源管理器中找到EJBTester.java。右鍵單擊EJBTester類并選擇 run file 運(yùn)行文件 。
驗(yàn)證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)
更多建議: