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。
在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 );
@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; } ... }
讓我們創(chuàng)建一個(gè)測(cè)試 EJB 應(yīng)用程序來(lái)測(cè)試 EJB 3.0 中的實(shí)體關(guān)系對(duì)象。
步驟 | 描述 |
---|---|
1 | 用包com.tutorialspoint.entity下一個(gè)名字EjbComponent在EJB作為解釋的創(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。 |
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)自動(dòng)創(chuàng)建一個(gè)JNDI條目- LibraryPersistentBean/remote。
我們將使用這個(gè)查詢(xún)字符串獲取遠(yuǎn)程業(yè)務(wù)類(lèi)型的對(duì)象- 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
這些屬性是用來(lái)初始化java命名服務(wù)的InitialContext對(duì)象
InitialContext對(duì)象將用于查找無(wú)狀態(tài)會(huì)話(huà)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 加載屬性并初始化輸出對(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()方法并退出。
在項(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)
更多建議: