一. 介紹html
百度了一下關於在NetBean開發環境裏建立EJB的教程,沒有找到好的例子,2天的調試過程,寫下來幫助後人。java
EJB (Enterprise Java Bean) 是一套高擴展性的開發企業級應用的開發結構,一般部署在JBoss, Glassfish, WildFly等服務器上, 更多介紹可參看連接。數據庫
1. Entity Bean: 域模型對象,用於實現O/R映射,負責將數據庫中的表記錄映射爲內存中的Entity對象,事實上,建立一個Entity Bean對象至關於新建一條記錄,刪除一個Entity Bean會同時從數據庫中刪除對應記錄,修改一個Entity Bean時,容器會自動將Entity Bean的狀態和數據庫同步。瀏覽器
2. Session Bean: 用於實現業務邏輯,它能夠是有狀態的,也能夠是無狀態的。每當客戶端請求時,容器就會選擇一個Session Bean來爲客戶端服務。Session Bean能夠直接訪問數據庫,但更多時候,它會經過Entity Bean實現數據訪問。服務器
3. Message Driven Bean: MDB是EJB2.0中引入的新的企業Bean,它基於JMS消息,只能接收客戶端發送的JMS消息而後處理。MDB其實是一個異步的無狀態Session Bean,客戶端調用MDB後無需等待,馬上返回,MDB將異步處理客戶請求。這適合於須要異步處理請求的場合,好比訂單處理,這樣就能避免客戶端長時間的等待一個方法調用直到返回結果。 session
二. 建立EJB模塊less
點擊File --> New Project, 在Java EE目錄下選擇EJB Module:異步
給項目取一個名字Sample-EJB,選擇合適的項目目錄,而後點擊下一步編輯器
選擇Server, 我選的是GlassFish Server 4.1, Java EE Version是Jave EE 7.ide
三. 建立Application Class Library項目
點擊File --> New Project, 在Java目錄下選擇Java Class Library:
給項目取一個名字Sample-Client,選擇合適的項目目錄,而後點擊Next:
四. 建立Entity Bean
接下來建立一個Peoplede的entity class. Antity Class 通常對應了數據庫的一個表,當你建立Entity Class 後NetBeans IDE會給該類添加@Entity標記來表示它是一個Entity類.
每個Entity Class都必須有primary key. IDE會添加@ID標籤在primary key上面, @GeneratedValue來表示primary key 是怎麼產生的.
右擊Projects窗口的Sample-Client --> New --> Other選擇Persistence目錄裏的Entity Class:
下面的Create Persistence Unit能夠不選擇!
當點擊Finish後,IDE會打開People.java文件編輯器,對People.java作以下修改:
1 /* 2 * To change this license header, choose License Headers in Project Properties. 3 * To change this template file, choose Tools | Templates 4 * and open the template in the editor. 5 */ 6 package com.bruceyo.example.entity; 7 8 import java.io.Serializable; 9 import javax.persistence.Entity; 10 import javax.persistence.GeneratedValue; 11 import javax.persistence.GenerationType; 12 import javax.persistence.Id; 13 14 /** 15 * 16 * @author bruce_000 17 */ 18 @Entity 19 public class People implements Serializable { 20 private static final long serialVersionUID = 1L; 21 @Id 22 @GeneratedValue(strategy = GenerationType.AUTO) 23 private Long id; 24 private String firstName; 25 26 public String getFirstName() { 27 return firstName; 28 } 29 30 public void setFirstName(String firstName) { 31 this.firstName = firstName; 32 } 33 34 public String getLastName() { 35 return lastName; 36 } 37 38 public void setLastName(String lastName) { 39 this.lastName = lastName; 40 } 41 private String lastName; 42 43 public Long getId() { 44 return id; 45 } 46 47 public void setId(Long id) { 48 this.id = id; 49 } 50 51 @Override 52 public int hashCode() { 53 int hash = 0; 54 hash += (id != null ? id.hashCode() : 0); 55 return hash; 56 } 57 58 @Override 59 public boolean equals(Object object) { 60 // TODO: Warning - this method won't work in the case the id fields are not set 61 if (!(object instanceof People)) { 62 return false; 63 } 64 People other = (People) object; 65 if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { 66 return false; 67 } 68 return true; 69 } 70 71 @Override 72 public String toString() { 73 return "com.bruceyo.example.entity.Customer[ id=" + id + " ]"; 74 } 75 76 }
五. 建立Session Bean
EJB3.1可以輕鬆建立stateless的session bean, stateless session bean不保存相關用戶的狀態. 但它能夠保存它的實例的狀態.
一般用EJB Container來建立bean對象池,而後用對象池裏的對象來處理用戶請求.
右擊Projects窗口的Sample-EJB --> New --> Other選擇Enterprise JavaBean目錄裏的Session Bean:
給EJB取名字叫AccountService, 並寫上包名; 選擇Stateless, 同時下面的Remote in Project要選上!
按finish後,IDE會打開AccountService.java文件編輯器, 修改文件以下:
1 /* 2 * To change this license header, choose License Headers in Project Properties. 3 * To change this template file, choose Tools | Templates 4 * and open the template in the editor. 5 */ 6 package com.bruceyo.sample.service; 7 8 import com.bruceyo.example.entity.People; 9 import javax.ejb.Stateless; 10 import javax.persistence.EntityManager; 11 import javax.persistence.PersistenceContext; 12 13 /** 14 * 15 * @author bruce_000 16 */ 17 @Stateless 18 public class AccountService implements AccountServiceRemote { 19 20 @PersistenceContext 21 private EntityManager em; 22 23 @Override 24 public People createAccount(String firstName, String lastName) { 25 People customer = new People(); 26 customer.setFirstName(firstName); 27 customer.setLastName(lastName); 28 29 em.persist(customer); 30 return customer; 31 } 32 33 // Add business logic below. (Right-click in editor and choose 34 // "Insert Code > Add Business Method") 35 }
六. 建立持久單元Persistence Unit
建立一個Persistence Unit做爲數據源的容器來管理Entities,
右擊Projects窗口的Sample-EJB --> New --> Other選擇Persistence目錄裏的Persistence Unit:
選擇Data Source爲jdbc/sample; 勾選Drop and Create, 若是數據庫裏有的話就丟棄原來的,記得查看下jdbc/sample裏有哪些表!EJB的
打開剛剛建立的persistence.xml, 去掉Include All Entity Classes的勾,而後添加Entity Class.
結果以下:
七. 部署(Deploy) EJB模塊
右鍵EJB模塊,選擇Build --> Deploy, NetBeans會自動部署EJB服務,能夠到Services窗口查看GlassFish本地服務器有沒有自動開啓.
八. 建立一個Servlet Class來測試EJB
1, 建立一個Web Module:
點擊File --> New Project, 在Java Web目錄下選擇Web Application:
添加項目名字Sample-Web, 選擇合適的項目位置:
點擊下一步,添加Context Path: /Sample-Web, 部署Web Application的時候要用到這個路徑訪問網站.
2, 建立 Servlet
右擊Projects窗口的Sample-EJB --> New --> Other選擇Enterprise JavaBean目錄裏的Session Bean:
點擊Next--> Finish後,IDE打開AccountController.java的編輯器,修改以下:
1 /* 2 * To change this license header, choose License Headers in Project Properties. 3 * To change this template file, choose Tools | Templates 4 * and open the template in the editor. 5 */ 6 package com.bruceyo.example.tester; 7 8 import com.bruceyo.example.entity.People; 9 import com.bruceyo.sample.service.AccountServiceRemote; 10 import java.io.IOException; 11 import java.io.PrintWriter; 12 import javax.ejb.EJB; 13 import javax.servlet.ServletException; 14 import javax.servlet.annotation.WebServlet; 15 import javax.servlet.http.HttpServlet; 16 import javax.servlet.http.HttpServletRequest; 17 import javax.servlet.http.HttpServletResponse; 18 19 /** 20 * 21 * @author jGauravGupta 22 */ 23 @WebServlet(name = "AccountController", urlPatterns = {"/AccountController"}) 24 public class AccountController extends HttpServlet { 25 @EJB 26 private AccountServiceRemote accountService; 27 28 29 /** 30 * Handles the HTTP <code>POST</code> method. 31 * 32 * @param request servlet request 33 * @param response servlet response 34 * @throws ServletException if a servlet-specific error occurs 35 * @throws IOException if an I/O error occurs 36 */ 37 @Override 38 protected void doPost(HttpServletRequest request, HttpServletResponse response) 39 throws ServletException, IOException { 40 response.setContentType("text/html;charset=UTF-8"); 41 try (PrintWriter out = response.getWriter()) { 42 String firstName = request.getParameter("firstName"); 43 String lastName = request.getParameter("lastName"); 44 45 People customer = accountService.createAccount(firstName, lastName); 46 out.println("Customer["+customer.getFirstName()+"] : " + customer.getId()); 47 } 48 } 49 50 }
九. 添加HTML頁面
編輯Sample-Web裏的Index.html網頁文件以下:
1 <!DOCTYPE html> 2 <!-- 3 To change this license header, choose License Headers in Project Properties. 4 To change this template file, choose Tools | Templates 5 and open the template in the editor. 6 --> 7 <html> 8 <head> 9 <title>TODO supply a title</title> 10 <meta charset="UTF-8"> 11 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 12 </head> 13 <body> 14 <form action="AccountController" method="post" > 15 <input type="text" name="firstName" placeholder="First Name" /> 16 <input type="text" name="lastName" placeholder="Last Name"/> 17 <input type="submit" value="Create"/> 18 </form> 19 </body> 20 </html>
而後右擊Sample-Web, Build --> Deploy --> Run或在瀏覽器輸入網址 http://localhost:8080/Sample-Web/
十. 運行代碼結果
-->
此時若是查看Services --> Databases --> jdbc:derby... --> sample --> People, 能看到JPA已經添加了一條數據到數據庫