EJB3.0,EJB查詢語言編寫自定義的查詢非常方便,不用擔心底層資料庫的詳細資訊。這是很相似的HQL(Hibernate查詢語言),通常被稱為按名稱EJBQL。
要理解熟悉ejb的EJBQL,要做好以下幾項工作。
-
步驟 1. 在資料庫中創建表.
-
步驟 2. 創建一個無狀態EJB.
-
步驟 3. 更新無狀態的EJB。添加添加記錄並獲得通過實體管理器從資料庫中記錄的方法。
-
步驟 4. 一個基於控制臺應用程式客戶端將訪問無狀態EJB的持久化資料庫中的數據。
創建資料庫表
創建表 books 在默認資料庫 postgres.
CREATE TABLE books ( id integer PRIMARY KEY, name varchar(50) );
創建模型類
public class Book implements Serializable{
private int id;
private String name;
public Book(){
}
public int getId() {
return id;
}
...
}
創建無狀態EJB
@Stateless
public class LibraryPersistentBean implements LibraryPersistentBeanRemote {
public void addBook(Book book) {
//persist book using entity manager
}
public List<Book> getBooks() {
//get books using entity manager
}
...
}
構建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 data access 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 chapter and modify them as shown below. |
| 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. Modify it as shown below. |
EJBComponent (EJB Module)
Book.java
package com.tutorialspoint.entity;
import java.io.Serializable;
public class Book implements Serializable{
private int id;
private String name;
public Book(){
}
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<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;
import javax.persistence.Query;
@Stateless
public class LibraryPersistentBean implements LibraryPersistentBeanRemote {
public LibraryPersistentBean(){
}
@PersistenceContext(unitName="EntityEjbPU")
private EntityManager entityManager;
public void addBook(Book book) {
entityManager.persist(book);
}
public List<Book> getBooks() {
//create an ejbql expression
String ejbQL = "From Book b where b.name like ?1";
//create query
Query query = entityManager.createQuery(ejbQL);
//substitute parameter.
query.setParameter(1, "%test%");
//execute the query
return query.getResultList();
}
}
-
只要在JBoss部署 EjbComponent專案,會注意到jboss的日誌。
-
JBoss已經自動為我們的會話bean創建一個JNDI條目 -LibraryPersistentBean/remote.
-
我們將使用這個查詢字串來獲得遠程類型的業務對象 -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 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
-
這些屬性是用來初始化InitialContext對象的Java命名服務
-
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
1. Add Book
2. Exit
Enter 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<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());
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()方法,JNDI名稱進行查找 - "LibraryStatelessSessionBean/remote" 以獲得遠程業務對象(狀態EJB)。
-
然後用戶顯示一個庫存儲的用戶介面和他/她被要求輸入選擇。
-
如果用戶輸入1,系統要求輸入書籍名稱和節省了使用無狀態的會話bean addBook()方法。會話Bean堅持這本書中通過EntityManager的調用資料庫。
-
如果用戶輸入2,系統檢索書使用狀態會話Bean getBooks()方法和退出。
-
然後另一個JNDI名稱進行查找 - "LibraryStatelessSessionBean/remote"獲得遠程業務對象(狀態EJB)再次列出書籍。
運行客戶端訪問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 Testing ********************** Welcome to Book Store ********************** Options 1. Add Book 2. Exit Enter Choice: 2 Book(s) entered so far: 1 1. learn Testing BUILD SUCCESSFUL (total time: 15 seconds)
