EJB实体关系
EJB 3.0中提供的选项来定义像一对一的数据库实体关系/映射,一对多,多对一和多对多关系。以下是相关的注释。
-
OneToOne - 对象都具有一对一的关系。例如,乘客可以在时间旅行使用一张票。
-
OneToMany - 对象是具有一对多的关系。例如,一个父亲可以有多个孩子。
-
ManyToOne - 对象有多对一的关系。举例来说,多个孩子对一个母亲。
-
ManyToMany - 对象是多对多的关系。举例来说,一本书可以多发作者,一个作者可以写多本书。
在这里,我们将演示如何使用多对多的映射。要代表多对多的关系,三表是必需的。
-
Book - 书籍记录表
-
Author - 作者Author表记录
-
Book_Author - BOOK_AUTHOR上述Book和Author表的表具有关联。
创建表
创建表book author, book_author 在默认数据库 postgres.
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; ... }
Use ManyToMany annotation in Book Entity
@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应用程序来测试EJB3.0实体关系对象。
Step | 描述 |
---|---|
1 | Create a project with a name EjbComponent under a package com.tutorialspoint.entity as explained in the EJB - Create Application chapter. Please use the project created in EJB - Persistence chapter as such for this chapter to understand embedded objects in ejb concepts. |
2 | Create Author.java under package com.tutorialspoint.entity as explained in the EJB - Create Application chapter. Keep rest of the files unchanged. |
3 | Create Book.java under package com.tutorialspoint.entity. Use EJB - Persistence chapter as reference. Keep rest of the files unchanged. |
4 | Clean and Build the application to make sure business logic is working as per the requirements. |
5 | Finally, deploy the application in the form of jar file on JBoss Application Server. JBoss Application server will get started automatically if it is not started yet. |
6 | Now create the ejb client, a console based application in the same way as explained in theEJB - Create Application chapter under topic Create Client to access EJB. |
EJBComponent (EJB Module)
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 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
-
These properties are used to initialize the InitialContext object of java naming service
-
InitialContext object will be used to lookup stateless session 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做以下任务。
-
jndi.properties中加载和初始化的InitialContext对象。
-
在testInterceptedEjb()方法,JNDI查找名称 - 的“LibraryPersistenceBean/远程”获得远程业务对象(无状态的EJB)。
-
然后用户显示一个库存储的用户界面和他/她被要求输入选择。
-
如果用户输入1,系统要求输入书籍名称和节约使用无状态的会话bean addBook()方法的书。会话Bean在数据库中存储的书。
-
如果用户输入2,系统检索书使用状态会话Bean getBooks()方法和退出。
运行客户端访问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 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)
欢迎任何形式的转载,但请务必注明出处,尊重他人劳动共创优秀实例教程
转载请注明:文章转载自:代码驿站 [http:/www.codeinn.net]
本文标题:EJB实体关系
本文地址:http://www.codeinn.net/ejb/727.html