目標:使用Java持久性API把數據庫中的數據顯示出來(lái)。
基本過(guò)程包括:
u 加載驅動(dòng)程序
u 創(chuàng )建數據庫以及表
u 在NetBeans中加載驅動(dòng)程序
u 在NetBeans中創(chuàng )建連接
u 創(chuàng )建持久單元以及實(shí)體類(lèi)
u 創(chuàng )建訪(fǎng)問(wèn)持久單元的會(huì )話(huà)Bean
u 創(chuàng )建Servlet客戶(hù)端程序,訪(fǎng)問(wèn)會(huì )話(huà)Bean,并顯示結果
1、放JDBC驅動(dòng)程序到下面的目錄
根據自己的安裝目錄進(jìn)行修改。如果采用默認安裝,應該放在下面的目錄下。
C:/Sun/AppServer/domains/domain1/lib/ext
2、在MySQL數據庫中添加數據庫entity
create database entity
3、創(chuàng )建表userinfo
在entity數據庫中創(chuàng )建表,表結構與書(shū)上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中添加驅動(dòng)程序
在Drivers上面點(diǎn)擊右鍵,選擇New Driver。選擇JDBC驅動(dòng)程序所在的jar壓縮包。
5、添加連接
在上圖的Databases上點(diǎn)擊右鍵選擇New Connection,在彈出的界面上選擇前面添加的驅動(dòng)程序,然后修改URL,修改后:jdbc:mysql://localhost:3306/entity。
其中:localhost表示主機,3306表示端口,entity表示數據庫。
6、創(chuàng )建EJB Module
選擇FileàNew Project,選擇中間的Enterprise,然后選擇右邊的EJB Module。工程的名字是UserSession。
7、創(chuàng )建持久單元
在工程上面點(diǎn)擊右鍵,選擇NewàFile/Folder,選擇中間的Persistence,右邊選擇Persistence Unit。在彈出的界面中,選擇數據源:選擇New DataSource。在彈出的界面中輸入一個(gè)JNDI名字entity2,然后選擇前面第5步創(chuàng )建好的連接。
生成的文件如下:
<?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、創(chuàng )建持久類(lèi)
在工程上面點(diǎn)擊右鍵,選擇New,然后選擇Entity Class from DataBase。在DataSource中選擇剛才配置好的數據源entity2。然后在左下方會(huì )出現表,選擇中間的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 按鈕,點(diǎn)擊該按鈕,然后把剛創(chuàng )建好的實(shí)體類(lèi)添加到持久單元中。
9、編寫(xiě)會(huì )話(huà)Bean訪(fǎng)問(wèn)該實(shí)體
在該工程中添加一個(gè)會(huì )話(huà)Bean,添加過(guò)程參考會(huì )話(huà)Bean的編寫(xiě),Bean的名字是UserManager,提供Remote接口。
在該會(huì )話(huà)Bean中添加一個(gè)業(yè)務(wù)方法,下面是修改后的文件,紅色部分是添加的。
9.1 接口文件
package jpa;
import javax.ejb.Remote;
import java.util.List;
/**
* This is the business interface for UserManager enterprise bean.
*/
@Remote
public interface UserManagerRemote {
public List<Userinfo> findAllUser();
}
9.2 Bean類(lèi)
/*
* 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
*/
@Stateless
public 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、編寫(xiě)Servlet客戶(hù)端訪(fǎng)問(wèn)會(huì )話(huà)Bean
需要引入會(huì )話(huà)Bean的客戶(hù)端程序,可以在Web應用的Liberaries上點(diǎn)擊右鍵,選擇Add Project,如下面的界面,選擇前面創(chuàng )建的EJB模塊,選擇添加即可(這樣就不用拷貝會(huì )話(huà)Bean的接口文件了)。
然后在工程里面添加一個(gè)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模塊,訪(fǎng)問(wèn)Servlet可以得到用戶(hù)列表。
更多內容可以參考本人的書(shū)《Java EE 5實(shí)用教程——基于WebLogic和Eclipse》