DAO的全称是Data Access Object ,数据访问对象,主要功能是数据操作,在程序的标准开发中属于数据层的操作,开发框架如图:
其中业务层全称是Business Object ,业务对象,可以将多个原子性的DAO操作进行组合,形成一个完整的业务逻辑。
数据层:提供多个原子性的DAO操作,例如增加、删除、修改等,都是原子性的操作。对于一些小型的系统,一般只使用DAO模式就足够,而对于大型数据系统,业务关联较多时,则要使用BO进行操作。
在整个的DAO设计模式中,使用的是接口进行操作,客户端使用接口,服务端也使用接口实现业务逻辑。DAO主要由以下几个部分组成:
DatabaseConnection:专门负责数据库的打开与关闭操作的类;
VO:主要由属性、setter、getter等构成,VO中的属性与表中的字段相对应,每一个VO类的对象都表示表中的一条记录;
DAO:主要定义操作的接口,定义数据库的原子性,增删改查等都是原子性的体现;
Impl:DAO接口的真实实现类,完成具体的数据库操作,但是不负责数据库的打开和关闭;
Proxy:代理实现,负责数据库的打开和关闭,调用真实实现类对象的操作;
Factory:通过工厂类取得一个DAO的实例化对象。
创建名为emp的表,列名有:empno、ename、job、hiredate、sal。
Emp.java
package com.zzh.test; import java.util.Date; public class Emp { private int empno; private String ename; private String job; private Date hiredate; private float sal; public int getEmpno() { return empno; } public void setEmpno(int empno) { this.empno = empno; } public String getEname() { return ename; } public void setEname(String ename) { this.ename = ename; } public String getJob() { return job; } public void setJob(String job) { this.job = job; } public Date getHiredate() { return hiredate; } public void setHiredate(Date hiredate) { this.hiredate = hiredate; } public float getSal() { return sal; } public void setSal(float sal) { this.sal = sal; } }
package com.zzh.test; import java.sql.Connection; import java.sql.DriverManager; public class DatabaseConnection { public static final String DBDRIVER = "com.mysql.jdbc.Driver"; public static final String DBURL = "jdbc:mysql://localhost:3306/test"; public static final String DBUSER = "用户名"; public static final String DBPASS = "密码"; private Connection conn = null; public DatabaseConnection() throws Exception { try { Class.forName(DBDRIVER); this.conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS); } catch (Exception e) { throw e; } } public Connection getConnection() { return this.conn; } public void close() throws Exception { if (this.conn != null) { try { this.conn.close(); } catch (Exception e) { throw e; } } } }
package com.zzh.test; import java.util.List; public interface IEmpDAO { //定义DAO操作标准 /* * 数据库的增加操作,一般用doXxx的方式命名 */ public boolean doCreate(Emp emp) throws Exception; /* * 数据库的查询操作,一般用findXxx的方式命名 */ public List<Emp> findAll(String keyWord) throws Exception; /* * 根据编号查询信息 */ public Emp findById(int empno) throws Exception; }
package com.zzh.test; import java.sql.Connection; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; import com.mysql.jdbc.PreparedStatement; public class EmpDAOImpl implements IEmpDAO { private Connection conn = null; private PreparedStatement pstmt = null; public EmpDAOImpl(Connection conn) { this.conn = conn; } @Override public boolean doCreate(Emp emp) throws Exception { // TODO Auto-generated method stub boolean flag = false; String sql = "INSERT INTO emp(empno,ename,job,hiredate,sal)VALUES(?,?,?,?,?)"; this.pstmt = (PreparedStatement) 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; } @Override public List<Emp> findAll(String keyWord) throws Exception { // TODO Auto-generated method stub List<Emp> all = new ArrayList<Emp>(); String sql = "SELECT empno,ename,job,hiredate,sal FROM emp WHERE ename LIKE ? OR job LIKE ?"; this.pstmt = (PreparedStatement) 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; } @Override public Emp findById(int empno) throws Exception { // TODO Auto-generated method stub Emp emp = null; String sql = "SELECT empno,ename,job,hiredate,sal FROM emp WHERE empno = ?"; this.pstmt = (PreparedStatement) 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; } }
package com.zzh.test; import java.util.*; import java.sql.*; 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; } }
package com.zzh.test; public class DAOFactory { public static IEmpDAO getIEmpDAOInstance() throws Exception { return new EmpDAOProxy(); } }
package com.zzh.test; 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("luna-" + x); emp.setJob("产品经理-" + x); emp.setHiredate(new java.util.Date()); emp.setSal(500 * x); DAOFactory.getIEmpDAOInstance().doCreate(emp); } } }运行结果:
TestDAOSelect.java
package com.zzh.test; import java.util.Iterator; import java.util.List; public class TestDAOSelect { public static void main(String[] args) throws Exception { // TODO Auto-generated method stub 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.getEname()); } } }运行结果:
<%@ page language="java" contentType="text/html; charset=GBK" pageEncoding="GBK"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=GBK"> <title>emp_insert</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 import="java.text.SimpleDateFormat"%> <%@page import="com.zzh.test.*"%> <%@ page language="java" contentType="text/html; charset=GBK" pageEncoding="GBK"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=GBK"> <title>emp_insert_do</title> </head> <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>
<%@ page contentType="text/html" pageEncoding="GBK"%> <%@page import="java.text.SimpleDateFormat"%> <%@page import="com.zzh.test.*"%> <%@page import="java.util.*"%> <html> <head><title>emp_list</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>运行结果: