Model1方式實現DAO設計模式

GeekWay發表於2013-07-04
DAO由以下幾個部分組成:
DatabaseConnection:專門負責資料庫的開啟和關閉操作的類,僅此而已,不參與資料庫的其他操作。
VO:主要由屬性、setter、getter方法組成,VO類中的屬性與表中的欄位相對應,每一個VO類物件都表示表中的每一條記錄。
DAO:主要定義操作的介面,定義一系列資料庫的原子性操作,如增加、修改、刪除、按ID查詢等。
Impl:DAO介面的真是實現類,完成具體的資料庫操作,但是不負責資料庫的開啟和關閉(因為已經由DatabaseConnection完成了)。
Proxy:代理實現類,主要完成資料庫的開啟和關閉,並且呼叫真實實現類物件的操作。
Factory:工程類,通過工廠類取得一個DAO的例項化物件。

下面通過一個簡單的例子說明這一點,客戶端負責對資料的顯示、插入等操作。相關類圖如下所示:

emp.java

package wml.vo ;
import java.util.Date ;
public class Emp {
	private int empno ;
	private String ename ;
	private String job ;
	private Date hiredate ;
	private float sal ;
	public void setEmpno(int empno){
		this.empno = empno ;
	}
	public void setEname(String ename){
		this.ename = ename ;
	}
	public void setJob(String job){
		this.job = job ;
	}
	public void setHiredate(Date hiredate){
		this.hiredate = hiredate ;
	}
	public void setSal(float sal){
		this.sal = sal ;
	}
	public int getEmpno(){
		return this.empno ;
	}
	public String getEname(){
		return this.ename ;
	}
	public String getJob(){
		return this.job ;
	}
	public Date getHiredate(){
		return this.hiredate ;
	}
	public float getSal(){
		return this.sal ;
	}
}

DatabaseConnection.java
package wml.dbc ;
import java.sql.Connection ;
import java.sql.DriverManager ;
public class DatabaseConnection {
	private static final String DBDRIVER = "org.gjt.mm.mysql.Driver" ; 
	private static final String DBURL = "jdbc:mysql://localhost:3306/mldn" ;
	private static final String DBUSER = "root" ;
	private static final String DBPASSWORD = "mysqladmin" ;
	private Connection conn ;
	public DatabaseConnection() throws Exception {
		Class.forName(DBDRIVER) ;
		this.conn = DriverManager.getConnection(DBURL,DBUSER,DBPASSWORD) ;
	}
	public Connection getConnection(){
		return this.conn ;
	}
	public void close() throws Exception {
		if(this.conn != null){
			try{
				this.conn.close() ;
			}catch(Exception e){
				throw e ;
			}
		}
	}
}

IEmpDAO.java
package wml.dao ;
import java.util.* ;
import wml.vo.* ;
public interface IEmpDAO {
	public boolean doCreate(Emp emp) throws Exception ;
	public List<Emp> findAll(String keyWord) throws Exception ;
	public Emp findById(int empno) throws Exception ;
}

EmpDAOImpl.java
package wml.impl ;
import java.util.* ;
import java.sql.* ;
import wml.dao.* ;
import wml.vo.* ;

public class EmpDAOImpl implements IEmpDAO {
	private Connection conn = null ;
	private PreparedStatement pstmt = null ;
	public EmpDAOImpl(Connection conn){
		this.conn = conn ;
	}
	public boolean doCreate(Emp emp) throws Exception{
		boolean flag = false ;
		String sql = "INSERT INTO emp(empno,ename,job,hiredate,sal) VALUES (?,?,?,?,?)" ;
		this.pstmt = this.conn.prepareStatement(sql) ;
		this.pstmt.setInt(1,emp.getEmpno()) ;
		this.pstmt.setString(2,emp.getEname()) ;
		this.pstmt.setString(3,emp.getJob()) ;
		this.pstmt.setDate(4,new java.sql.Date(emp.getHiredate().getTime())) ;
		this.pstmt.setFloat(5,emp.getSal()) ;
		if(this.pstmt.executeUpdate() > 0){
			flag = true ;
		}
		this.pstmt.close() ;
		return flag ;
	}
	public List<Emp> findAll(String keyWord) throws Exception{
		List<Emp> all = new ArrayList<Emp>() ;
		String sql = "SELECT empno,ename,job,hiredate,sal FROM emp WHERE ename LIKE ? OR job LIKE ?" ;
		this.pstmt = this.conn.prepareStatement(sql) ;
		this.pstmt.setString(1,"%"+keyWord+"%") ;
		this.pstmt.setString(2,"%"+keyWord+"%") ;
		ResultSet rs = this.pstmt.executeQuery() ;
		Emp emp = null ;
		while(rs.next()){
			emp = new Emp() ;
			emp.setEmpno(rs.getInt(1)) ;
			emp.setEname(rs.getString(2)) ;
			emp.setJob(rs.getString(3)) ;
			emp.setHiredate(rs.getDate(4)) ;
			emp.setSal(rs.getFloat(5)) ;
			all.add(emp) ;
		}
		this.pstmt.close() ;
		return all ;
	}
	public Emp findById(int empno) throws Exception{
		Emp emp = null ;
		String sql = "SELECT empno,ename,job,hiredate,sal FROM emp WHERE empno=?" ;
		this.pstmt = this.conn.prepareStatement(sql) ;
		this.pstmt.setInt(1,empno) ;
		ResultSet rs = this.pstmt.executeQuery() ;
		if(rs.next()){
			emp = new Emp() ;
			emp.setEmpno(rs.getInt(1)) ;
			emp.setEname(rs.getString(2)) ;
			emp.setJob(rs.getString(3)) ;
			emp.setHiredate(rs.getDate(4)) ;
			emp.setSal(rs.getFloat(5)) ;
		}
		this.pstmt.close() ;
		return emp ;
	}
}

EmpDAOProxy.java

package wml.proxy ;
import java.util.* ;
import java.sql.* ;
import wml.dao.* ;
import wml.dbc.* ;
import wml.dao.impl.* ;
import wml.vo.* ;

public class EmpDAOProxy implements IEmpDAO {
	private DatabaseConnection dbc = null ;
	private IEmpDAO dao = null ;	//真實主題
	public EmpDAOProxy() throws Exception {
		this.dbc = new DatabaseConnection() ;	//負責資料庫的開啟和關閉
		this.dao = new EmpDAOImpl(this.dbc.getConnection()) ;
	}
	public boolean doCreate(Emp emp) throws Exception{
		boolean flag = false ;
		try{
			if(this.dao.findById(emp.getEmpno()) == null){	//增加了“新增”前的判斷
				flag = this.dao.doCreate(emp) ;
			}
		}catch(Exception e){
			throw e ;
		}finally{
			this.dbc.close() ;
		}
		return flag ;
	}
	public List<Emp> findAll(String keyWord) throws Exception{
		List<Emp> all = null ;
		try{
			all = this.dao.findAll(keyWord) ;
		}catch(Exception e){
			throw e ;
		}finally{
			this.dbc.close() ;
		}
		return all ;
	}
	public Emp findById(int empno) throws Exception{
		Emp emp = null ;
		try{
			emp = this.dao.findById(empno) ;
		}catch(Exception e){
			throw e ;
		}finally{
			this.dbc.close() ;
		}
		return emp ;
	}
}

DAOFactory.java
package wml.factory ;
import wml.dao.IEmpDAO ;
import wml.dao.proxy.EmpDAOProxy ;
public class DAOFactory {
	public static IEmpDAO getIEmpDAOInstance() throws Exception{
		return new EmpDAOProxy() ;
	}
}

客戶端中的測試類如下:
(1)
TestDAOSelect.java
package cn.mldn.lxh.dao.test ;
import java.util.* ;
import wml.factory.DAOFactory ;
import wml.vo.* ;
public class TestDAOSelect{
	public static void main(String args[]) throws Exception{
		List<Emp> all = DAOFactory.getIEmpDAOInstance().findAll("") ;
		Iterator<Emp> iter = all.iterator() ;
		while(iter.hasNext()){
			Emp emp = iter.next() ;
			System.out.println(emp.getEmpno() + "、" + emp.getEname() + " --> " + emp.getJob()) ;
		}
	}
}

(2)
TestDAOInsert.java
package wml.dao.test ;
import wml.factory.DAOFactory ;
import wml.vo.* ;
public class TestDAOInsert{
	public static void main(String args[]) throws Exception{
		Emp emp = null ;
		for(int x=0;x<5;x++){
			emp = new Emp() ;
			emp.setEmpno(1000 + x) ;
			emp.setEname("Jefferson- " + x) ;
			emp.setJob("程式設計師 - " + x) ;
			emp.setHiredate(new java.util.Date()) ;
			emp.setSal(500 * x) ;
			DAOFactory.getIEmpDAOInstance().doCreate(emp) ;
		}
	}
}


JSP頁面如下:
查詢頁:
<%@ page contentType="text/html" pageEncoding="GBK"%>
<%@ page import="wml.factory.*,wml.vo.*"%>
<%@ page import="java.util.*"%>
<html>
<head><title>這是標題</title></head>
<%	request.setCharacterEncoding("GBK") ;	%>
<body>
<%
	String keyWord = request.getParameter("kw") ;
	if(keyWord == null){
		keyWord = "" ;	// 如果沒有查詢關鍵字,則查詢全部
	}
	List<Emp> all = DAOFactory.getIEmpDAOInstance().findAll(keyWord) ;
	Iterator<Emp> iter = all.iterator() ;
%>
<center>
<form action="emp_list.jsp" method="post">
	請輸入查詢關鍵字:<input type="text" name="kw">
	<input type="submit" value="查詢">
</form>
<table border="1" width="80%"> 
	<tr>
		<td>僱員編號</td>
		<td>僱員姓名</td>
		<td>僱員工作</td>
		<td>僱傭日期</td>
		<td>基本工資</td>
	</tr>
<%
	while(iter.hasNext()){
		Emp emp = iter.next() ;
%>
	<tr>
		<td><%=emp.getEmpno()%></td>
		<td><%=emp.getEname()%></td>
		<td><%=emp.getJob()%></td>
		<td><%=emp.getHiredate()%></td>
		<td><%=emp.getSal()%></td>
	</tr>
<%
	}
%>
</table>
</center>
</body>
</html>

插入頁:
<%@ page contentType="text/html" pageEncoding="GBK"%>
<html>
<head><title>這是標題</title></head>
<body>
<form action="emp_insert_do.jsp" method="post">
	僱員編號:<input type="text" name="empno"><br>
	僱員姓名:<input type="text" name="ename"><br>
	僱員職位:<input type="text" name="job"><br>
	僱傭日期:<input type="text" name="hiredate"><br>
	基本工資:<input type="text" name="sal"><br>
	<input type="submit" value="註冊">
	<input type="reset" value="重置">
</form>
</body>
</html>

<%@ page contentType="text/html" pageEncoding="GBK"%>
<%@ page import="cn.mldn.lxh.factory.*,cn.mldn.lxh.vo.*"%>
<%@ page import="java.text.*"%>
<html>
<head><title>這是標題</title></head>
<%	request.setCharacterEncoding("GBK");	%>
<body>
<%
	Emp emp = new Emp() ;
	emp.setEmpno(Integer.parseInt(request.getParameter("empno"))) ;
	emp.setEname(request.getParameter("ename")) ;
	emp.setJob(request.getParameter("job")) ;
	emp.setHiredate(new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("hiredate"))) ;
	emp.setSal(Float.parseFloat(request.getParameter("sal"))) ;
try{
	if(DAOFactory.getIEmpDAOInstance().doCreate(emp)){
%>
		<h3>僱員資訊新增成功!</h3>
<%
	} else {
%>
		<h3>僱員資訊新增失敗!</h3>
<%
	}
%>
<%
}catch(Exception e){
	e.printStackTrace() ;
}
%>
</body>
</html>





相關文章