目標:使用Java持久性API把資料庫中的資料顯示出來。基本過程包括:u 載入驅動程式u 建立資料庫以及表u 在NetBeans中載入驅動程式u 在NetBeans中建立串連u 建立持久單元以及實體類u 建立訪問持久單元的會話Beanu 建立Servlet用戶端程式,訪問會話Bean,並顯示結果
1、放JDBC驅動程式到下面的目錄根據自己的安裝目錄進行修改。如果採用預設安裝,應該放在下面的目錄下。C:/Sun/AppServer/domains/domain1/lib/ext
2、在MySQL資料庫中添加資料庫entitycreate database entity
3、建立表userinfo 在entity資料庫中建立表,表結構與書上25章的一樣,插入幾條測試資料。create table userinfo( userid varchar(10) primary key not null, username varchar(10) not null, userpass varchar(10) not null, usertype char(1) not null)插入如下測試資料:insert into userinfo values('user001','zhangsan','zhangsan','0');insert into userinfo values('user002','lisi','lisi','0');insert into userinfo values('admin001','mishu','mishu','0');
4、在NetBeans中添加驅動程式在Drivers上面點擊右鍵,選擇New Driver。選擇JDBC驅動程式所在的jar壓縮包。
5、添加串連在的Databases上點擊右鍵選擇New Connection,在彈出的介面上選擇前面添加的驅動程式,然後修改URL,修改後:jdbc:mysql://localhost:3306/entity。其中:localhost表示主機,3306表示連接埠,entity表示資料庫。
6、建立EJB Module 選擇FileàNew Project,選擇中間的Enterprise,然後選擇右邊的EJB Module。工程的名字是UserSession。
7、建立持久單元在工程上面點擊右鍵,選擇NewàFile/Folder,選擇中間的Persistence,右邊選擇Persistence Unit。在彈出的介面中,選擇資料來源:選擇New DataSource。在彈出的介面中輸入一個JNDI名字entity2,然後選擇前面第5步建立好的串連。產生的檔案如下:<?xml version="1.0" encoding="UTF-8"?><persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"> <persistence-unit name="UserPU" transaction-type="JTA"> <provider>oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider</provider> <jta-data-source>entity2</jta-data-source> <properties> <property name="toplink.ddl-generation" value="create-tables"/> </properties> </persistence-unit></persistence>
8、建立持久類在工程上面點擊右鍵,選擇New,然後選擇Entity Class from DataBase。在DataSource中選擇剛才配置好的資料來源entity2。然後在左下方會出現表,選擇中間的Add,添加到右邊。選擇下一步,然後完成即可。產生的檔案如下:/* * Userinfo.java * * Created on 2007年5月21日, 上午6:17 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package jpa; import java.io.Serializable;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.Id;import javax.persistence.NamedQueries;import javax.persistence.NamedQuery;import javax.persistence.Table; /** * Entity class Userinfo * * @author Administrator */@Entity@Table(name = "userinfo")@NamedQueries( { @NamedQuery(name = "Userinfo.findByUserid", query = "SELECT u FROM Userinfo u WHERE u.userid = :userid"), @NamedQuery(name = "Userinfo.findByUsername", query = "SELECT u FROM Userinfo u WHERE u.username = :username"), @NamedQuery(name = "Userinfo.findByUserpass", query = "SELECT u FROM Userinfo u WHERE u.userpass = :userpass"), @NamedQuery(name = "Userinfo.findByUsertype", query = "SELECT u FROM Userinfo u WHERE u.usertype = :usertype") })public class Userinfo implements Serializable { @Id @Column(name = "userid", nullable = false) private String userid; @Column(name = "username", nullable = false) private String username; @Column(name = "userpass", nullable = false) private String userpass; @Column(name = "usertype", nullable = false) private char usertype; /** Creates a new instance of Userinfo */ public Userinfo() { } /** * Creates a new instance of Userinfo with the specified values. * @param userid the userid of the Userinfo */ public Userinfo(String userid) { this.userid = userid; } /** * Creates a new instance of Userinfo with the specified values. * @param userid the userid of the Userinfo * @param username the username of the Userinfo * @param userpass the userpass of the Userinfo * @param usertype the usertype of the Userinfo */ public Userinfo(String userid, String username, String userpass, char usertype) { this.userid = userid; this.username = username; this.userpass = userpass; this.usertype = usertype; } /** * Gets the userid of this Userinfo. * @return the userid */ public String getUserid() { return this.userid; } /** * Sets the userid of this Userinfo to the specified value. * @param userid the new userid */ public void setUserid(String userid) { this.userid = userid; } /** * Gets the username of this Userinfo. * @return the username */ public String getUsername() { return this.username; } /** * Sets the username of this Userinfo to the specified value. * @param username the new username */ public void setUsername(String username) { this.username = username; } /** * Gets the userpass of this Userinfo. * @return the userpass */ public String getUserpass() { return this.userpass; } /** * Sets the userpass of this Userinfo to the specified value. * @param userpass the new userpass */ public void setUserpass(String userpass) { this.userpass = userpass; } /** * Gets the usertype of this Userinfo. * @return the usertype */ public char getUsertype() { return this.usertype; } /** * Sets the usertype of this Userinfo to the specified value. * @param usertype the new usertype */ public void setUsertype(char usertype) { this.usertype = usertype; } /** * Returns a hash code value for the object. This implementation computes * a hash code value based on the id fields in this object. * @return a hash code value for this object. */ @Override public int hashCode() { int hash = 0; hash += (this.userid != null ? this.userid.hashCode() : 0); return hash; } /** * Determines whether another object is equal to this Userinfo. The result is * <code>true</code> if and only if the argument is not null and is a Userinfo object that * has the same id field values as this object. * @param object the reference object with which to compare * @return <code>true</code> if this object is the same as the argument; * <code>false</code> otherwise. */ @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Userinfo)) { return false; } Userinfo other = (Userinfo)object; if (this.userid != other.userid && (this.userid == null || !this.userid.equals(other.userid))) return false; return true; } /** * Returns a string representation of the object. This implementation constructs * that representation based on the id fields. * @return a string representation of the object. */ @Override public String toString() { return "jpa.Userinfo[userid=" + userid + "]"; } }然後在Persistence.xml檔案的設計介面的下面有 Add Class 按鈕,點擊該按鈕,然後把剛建立好的實體類添加到持久單元中。
9、編寫會話Bean訪問該實體在該工程中添加一個會話Bean,添加過程參考會話Bean的編寫,Bean的名字是UserManager,提供Remote介面。在該會話Bean中添加一個業務方法,下面是修改後的檔案,紅色部分是添加的。
9.1 介面檔案package jpa; import javax.ejb.Remote;import java.util.List; /** * This is the business interface for UserManager enterprise bean. */@Remotepublic interface UserManagerRemote { public List<Userinfo> findAllUser();}
9.2 Bean類/* * UserManagerBean.java * * Created on 2007年5月21日, 上午6:18 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package jpa; import javax.ejb.Stateless;import javax.persistence.PersistenceContext;import javax.persistence.EntityManager;import java.util.List; /** * * @author Administrator */@Statelesspublic class UserManagerBean implements jpa.UserManagerRemote { @PersistenceContext EntityManager em; /** Creates a new instance of UserManagerBean */ public UserManagerBean() { } public List<Userinfo> findAllUser(){ return em.createQuery("select u from Userinfo u").getResultList(); } }
10
、編寫
Servlet
用戶端訪問會話
Bean需要引入會話Bean的用戶端程式,可以在Web應用的Liberaries上點擊右鍵,選擇Add Project,如下面的介面,選擇前面建立的EJB模組,選擇添加即可(這樣就不用拷貝會話Bean的介面檔案了)。然後在工程裡面添加一個Servlet,名字為FindAllUserServlet,修改後的代碼如下(紅色部分是添加的):/* * FindAllUserServlet.java * * Created on 2007年5月21日, 上午6:27 */ package jpa.web; import java.io.*;import java.net.*; import javax.servlet.*;import javax.servlet.http.*;import javax.ejb.EJB;import jpa.UserManagerRemote;import jpa.Userinfo;import java.util.List;import java.util.Iterator; /** * * @author Administrator * @version */public class FindAllUserServlet extends HttpServlet { @EJB UserManagerRemote user; /** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * @param request servlet request * @param response servlet response */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); List<Userinfo> list=user.findAllUser(); Iterator<Userinfo> i = list.iterator(); while(i.hasNext()){ Userinfo tmpUser = i.next(); out.print(tmpUser.getUserid()+"-"+tmpUser.getUsername()+"<br>"); } out.close(); } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** Handles the HTTP <code>GET</code> method. * @param request servlet request * @param response servlet response */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** Handles the HTTP <code>POST</code> method. * @param request servlet request * @param response servlet response */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** Returns a short description of the servlet. */ public String getServletInfo() { return "Short description"; } // </editor-fold>}
11、運行測試 分別部署EJB模組和Web模組,訪問Servlet可以得到使用者列表。更多內容可以參考本人的書《Java EE 5實用教程——基於WebLogic和Eclipse》