📜  EJB-持久性

📅  最后修改于: 2020-11-16 06:15:34             🧑  作者: Mango


EJB 3.0是EJB 2.0中使用的实体bean,在很大程度上已由持久性机制代替。现在,实体bean是具有与表的映射关系的简单POJO。

以下是持久性API中的关键角色-

  • 实体-代表数据存储记录的持久对象。可序列化是一件好事。

  • EntityManager-持久性接口,可对持久性对象(实体)执行诸如添加/删除/更新/查找之类的数据操作。它还有助于使用查询界面执行查询。

  • 持久性单元(persistence.xml) -持久性单元描述了持久性机制的属性。

  • 数据源(* ds.xml) -数据源描述了与数据存储相关的属性,例如连接URL。用户名,密码等

为了演示EJB持久性机制,我们需要执行以下任务-

  • 步骤1-在数据库中创建表。

  • 步骤2-创建与表相对应的实体类。

  • 步骤3-创建数据源和持久性单元。

  • 步骤4-创建具有EntityManager实例的无状态EJB。

  • 步骤5-更新无状态EJB。添加方法以添加记录并通过实体管理器从数据库获取记录。

  • 步骤6-基于控制台的应用程序客户端将访问无状态EJB,以将数据持久存储在数据库中。

建立表格

在默认数据库postgres中创建一个表簿

CREATE TABLE books (
   id     integer PRIMARY KEY,
   name   varchar(50)
);

创建实体类

//mark it entity using Entity annotation 
//map table name using Table annotation
@Entity
@Table(name="books")
public class Book implements Serializable{
    
   private int id;
   private String name;

   public Book() {        
   }

   //mark id as primary key with autogenerated value
   //map database column id with id field
   @Id
   @GeneratedValue(strategy= GenerationType.IDENTITY)
   @Column(name="id")
   public int getId() {
      return id;
   }
   ...
}

创建数据源和持久性单元

数据源(jboss-ds.xml)



   
      PostgresDS
      jdbc:postgresql://localhost:5432/postgres
      org.postgresql.driver
      sa
      sa
      5
      20
      5
   

持久性单元(persistence.xml)



   
      java:/PostgresDS
      false
      
   
   
   
      org.hibernate.ejb.HibernatePersistence
      java:/PostgresDS
      false
      
      
         
      
   
   

创建具有EntityManager实例的无状态EJB

@Stateless
public class LibraryPersistentBean implements LibraryPersistentBeanRemote {
    
   //pass persistence unit to entityManager.
   @PersistenceContext(unitName="EjbComponentPU")
   private EntityManager entityManager;         

   public void addBook(Book book) {
      entityManager.persist(book);
   }    

   public List getBooks() {        
      return entityManager.createQuery("From Books").getResultList();
   }
   ...
}

构建EJB模块之后,我们需要一个客户端来访问无状态bean,这将在下一部分中创建。

应用范例

让我们创建一个测试EJB应用程序以测试EJB持久性机制。

Step Description
1

Create a project with a name EjbComponent under a package com.tutorialspoint.entity as explained in the EJB – Create Application chapter. You can also use the project created in EJB – Create Application chapter as such for this chapter to understand EJB persistence concepts.

2

Create Book.java under package com.tutorialspoint.entity and modify it as shown below.

3

Create LibraryPersistentBean.java and LibraryPersistentBeanRemote as explained in the EJB – Create Application chapters and modify them as shown below.

4

Create jboss-ds.xml in EjbComponent > setup folder and persistence.xml in EjbComponent > src > conf folder. These folders can be seen in files tab in Netbeans. Modify these files as shown above.

5

Clean and Build the application to make sure business logic is working as per the requirements.

6

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.

7

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. Modify it as shown below.

EJBComponent(EJB模块)

Book.java

package com.tutorialspoint.entity;

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="books")
public class Book implements Serializable{
    
   private int id;
   private String name;

   public Book() {        
   }

   @Id
   @GeneratedValue(strategy= GenerationType.IDENTITY)
   @Column(name="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;
   }    
}

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 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 getBooks() {
      return entityManager.createQuery("From Book").getResultList();
   }
}
  • 在JBOSS上部署EjbComponent项目后,请注意jboss日志。

  • JBoss已经为我们的会话bean- LibraryPersistentBean / remote自动创建了一个JNDI条目。

  • 我们将使用此查找字符串获取类型为com.tutorialspoint.stateless.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.stateless.LibraryPersistentBeanRemote - EJB3.x Remote Business Interface
16:30:02,723 INFO  [SessionSpecContainer] Starting jboss.j2ee:jar=EjbComponent.jar,name=LibraryPersistentBeanRemote,service=EJB3
16:30:02,723 INFO  [EJBContainer] STARTED EJB: com.tutorialspoint.stateless.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.stateless.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.stateless.LibraryPersistentBeanRemote;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Properties;
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.testEntityEjb();
   }
   
   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 testEntityEjb() {

      try {
         int choice = 1; 

         LibraryPersistentBeanRemote libraryBean =
         LibraryPersistentBeanRemote)ctx.lookup("LibraryPersistentBean/remote");

         while (choice != 2) {
            String bookName;
            showGUI();
            String strChoice = brConsoleReader.readLine();
            choice = Integer.parseInt(strChoice);
            if (choice == 1) {
               System.out.print("Enter book name: ");
               bookName = brConsoleReader.readLine();
               Book book = new Book();
               book.setName(bookName);
               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());
            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对象。

  • 在testStatefulEjb()方法中,使用名称“ LibraryStatefulSessionBean /远程”完成jndi查找,以获取远程业务对象(有状态ejb)。

  • 然后,向用户显示一个库存储用户界面,并要求他/她输入选择。

  • 如果用户输入1,则系统要求输入书名并使用无状态会话bean addBook()方法保存书。会话Bean通过EntityManager调用将书籍保留在数据库中。

  • 如果用户输入2,则系统使用有状态会话bean getBooks()方法检索书籍并退出。

  • 然后,使用名称“ LibraryStatelessSessionBean / remote”完成另一个jndi查找,以再次获取远程业务对象(无状态EJB),并完成了书的清单。

运行客户端以访问EJB

在项目资源管理器中找到EJBTester.java。右键单击EJBTester类,然后选择运行文件

在Netbeans控制台中验证以下输出-

run:
**********************
Welcome to Book Store
**********************
Options 
1. Add Book
2. Exit 
Enter Choice: 1
Enter book name: Learn Java
**********************
Welcome to Book Store
**********************
Options 
1. Add Book
2. Exit 
Enter Choice: 2
Book(s) entered so far: 1
1. learn java
BUILD SUCCESSFUL (total time: 15 seconds)

再次运行客户端以访问EJB

访问EJB之前,请重新启动JBoss。

在项目资源管理器中找到EJBTester.java。右键单击EJBTester类,然后选择运行文件

在Netbeans控制台中验证以下输出。

run:
**********************
Welcome to Book Store
**********************
Options 
1. Add Book
2. Exit 
Enter Choice: 1
Enter book name: Learn Spring
**********************
Welcome to Book Store
**********************
Options 
1. Add Book
2. Exit 
Enter Choice: 2
Book(s) entered so far: 2
1. learn java
2. Learn Spring
BUILD SUCCESSFUL (total time: 15 seconds)

上面显示的输出表明,书籍正被存储在永久性存储中,并且已从数据库中检索到。