EJB实体关系

2018-12-09 15:12 更新

EJB 3.0提供了选项来定义数据库实体关系/映射,比如一对一,一对多,多对一和多对多的关系。以下是相关的注解。

  • One To One 一对一 -对象是一对一的关系。例如,乘客可以在旅行时使用一张单程票

  • One To Many 一对多 -对象是一对多关系例如一个父亲可以多个孩子

  • Many To One 多对一 -对象是关系例如多个孩子单身母亲

  • Many To Many 多对多 -对象是多对多的关系。举例来说,一本书可以多发作者和作者可以写多本图书。

我们将在这里展示使用多对多的映射。若要表示多对多关系三个需要。

  • Book 书表记录的书

  • Author 作者-作者有记录Author表 

  • BOOK_AUTHOR -具有上述书籍和作者表的链接表BOOK_AUTHOR。


创建表

BOOK_AUTHOR默认数据库的Postgres创建一个表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;
   ...   
}


本书实体使用多对多注释

@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用包com.tutorialspoint.entity下一个名字EjbComponentEJB作为解释的创建项目-创建应用程序一章。请使用EJB创建的项目-持久章这样本章了解EJB概念嵌入的对象。
2包下com.tutorialspoint.entity创建Author.java作为EJB解释-创建应用程序一章。保持不变的文件其余部分。
3包下com.tutorialspoint.entity创建Book.java。使用EJB -持久章作为参考。保持不变的文件其余部分。
4清理并生成应用程序,确保业务逻辑正在按要求。
5最后,部署JBoss应用服务器上的jar文件的形式应用。如果尚未启动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();
   }
}
  • 一旦你部署EjbComponent项目到JBoss上,注意jboss的日志。

  • JBoss已经自动创建一个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 
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 加载属性初始化输出对象

  • 在testInterceptedEjb()方法中,jndi查找名称——“"LibraryPersistenceBean/remote”来获取远程业务对象(无状态stateless 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)

以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号