📅  最后修改于: 2020-11-16 06:25:28             🧑  作者: Mango
EJB 3.0提供了一些选项来定义数据库实体关系/映射,例如一对一,一对多,多对一和多对多关系。
以下是相关的注释-
一对一-对象具有一对一关系。例如,乘客可以一次使用一张车票旅行。
一对多-对象具有一对多关系。例如,一个父亲可以有多个孩子。
多对一-对象具有多对一关系。例如,有一个孩子的多个孩子。
多对多-对象具有多对多关系。例如,一本书可以有多位作者,而一位作者可以写多本书。
我们将在此处演示ManyToMany映射的用法。为了表示ManyToMany关系,需要以下三个表-
书籍-书籍表,具有书籍记录。
作者-作者表,其中包含作者记录。
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 authors;
...
}
在图书实体中使用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 getAuthors() {
return authors;
}
...
}
让我们创建一个测试EJB应用程序以测试EJB 3.0中的实体关系对象。
Step | Description |
---|---|
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 the EJB – Create Application chapter under topic Create Client to access 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 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 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 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 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 getBooks() {
return entityManager.createQuery("From Book").getResultList();
}
}
在JBOSS上部署EjbComponent项目后,请注意jboss日志。
JBoss已经为我们的会话bean − LibraryPersistentBean / remote自动创建了一个JNDI条目。
我们将使用此查找字符串获取类型为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命名服务的InitialContext对象。
InitialContext对象将用于查找无状态会话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 \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 authors = new HashSet();
authors.add(author);
book.setAuthors(authors);
libraryBean.addBook(book);
} else if (choice == 2) {
break;
}
}
List 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
EJBTester执行以下任务-
从jndi.properties加载属性并初始化InitialContext对象。
在testInterceptedEjb()方法中,使用名称“ LibraryPersistenceBean /远程”完成jndi查找,以获取远程业务对象(无状态EJB)。
然后,向用户显示一个库存储用户界面,并要求他/她输入选择。
如果用户输入1,则系统会询问书名并使用无状态会话bean addBook()方法保存书。 Session Bean将书存储在数据库中。
如果用户输入2,则系统使用无状态会话bean getBooks()方法检索书籍并退出。
在项目资源管理器中找到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)