小结:实例解析DAO设计模式工作流程(无框架)


    昨儿学Spring感觉对DAO设计模式一知半解,就扒了框架自己写了一个实例。花了一整天时间,不过收获很大,趁着没忘赶紧记录一下,希望以后有时间再来改进。


一:概述:

    概念就不赘述了,网上有的是,就从测试程序下手 一步步分析一下。

    文件结构是按照Spring写的,也分dao、model、service,如下图:

从执行顺序上来说:

    首先是.service层:测试和JSP前台调用都只调用service层的方法,service里的代理给外界提供了统一的操作方法,而方法的具体实现是靠其余两个底层支撑的。(之所以分层,是因为以后需要存入数据库的对象不只只有上边的Student一个对象,也不只有oracle一种数据库,这样分层易于程序延展)

    第二是DAO层:DAO层封装了 “如何把一个对象存入数据库” 的办法。比如如何连接上数据路(比如oracle,DBConnection.java),如何把已知的Student对象存入刚刚已连接的数据库(前一个比如提到的,StudentDAOImp.java),StudentDAO的抽象方法(IStudentDAO.java) 和工厂类等

    最后是model层:就是个VO,告诉上层对应请求、要存储表中的Student具体是个什么。


二:从测试程序的执行顺序分析

1.测试程序中测试插入的部分(StudentDAOProxyTest.java):

这是测试程序的一部分,能看出是要把Student类的一个实例,传给工厂类产出的实例的doCreate()方法:

	@Test
	public void testDoCreate() throws Exception
	{	
		Student stu = null;
		
		for(int i=0;i<5;i++)
		{
			stu = new Student();
			stu.setStudentid(100+i);
			stu.setName("张"+i);
			stu.setAge(i);
			
			DAOFactory.getIStudentDAOInstance().doCreate(stu);//测试插入实例,从工厂类通过代理获得实例(目前符合I接口的只有StudentDAOImpl一种,不过很容易延展)
		};
	}



2.看看工厂生产的实例是什么玩意(DAOFactory.java):

    这是工厂DAOFactory.java 的全部内容,他只是生产了一个代理类的实例而已。

    我们没生产具体的StudentDAOImpl,是因为我们把指定到底要生产什么的任务交给了代理类

    通过动态代理(Spring使用xml)的指定,只有代理类知道具体要生产什么。从工厂类和更上层的接口来看,方法是统一的,也就是说不用因为更换一个具体的代理内容而重新写n多代码了,只要改个xml配置就行了,维护起来简单得多

package com.rt.daodemo.dao;

import com.rt.daodemo.dao.IStudentDAO;//引入接口
import com.rt.daodemo.service.StudentDAOProxy;//引入代理类

public class DAOFactory 
{
	public static IStudentDAO getIStudentDAOInstance() throws Exception
	{
		return new StudentDAOProxy();//返回代理
	}
}



3.代理类代理了什么(StudentDAOProxy.java):

    代理类制定了:我们到底用哪种方式实现

    代理类中首次出现了数据库连接,我指定了一种方法(下边介绍)

    也首次出现了业务实现的方法,但是没有具体执行。具体的执行交给*.impl(接口和具体实现下边分析)。


    看一下构造函数,我是手动指定的,这里如果能根据xml配置文件的变化,而更换实现的话:那么现在从代理类往上的所有方法就都统一了。

    这下只要配置文件(构造中的指定)规定的到位,代理类就可以代理n多的具体实现,而不用改一行源码


    还有一点补充,这首次出现了try-catch异常处理,是因为数据库在任何情况下,操作完都得关闭。而上层不知道具体的数据库业务,所以在这要统一处理。其余的一路throw 交给最上层统一管理。

package com.rt.daodemo.service;

import java.util.List;

import com.rt.daodemo.dao.DBConnection;
import com.rt.daodemo.dao.IStudentDAO;
import com.rt.daodemo.dao.impl.StudentDAOImpl;
import com.rt.daodemo.model.Student;
//代理类,指定具体用哪种方式实现
public class StudentDAOProxy implements IStudentDAO 
{
	private DBConnection dbcon = null;//自定义的数据库连接类
	private IStudentDAO dao = null;//自定义的dao接口
	
	public StudentDAOProxy() throws Exception//构造中指定了代理的内容,这里可以用动态方法指定,示例就偷懒指定了
	{
		this.dbcon = new DBConnection();
		this.dao = new StudentDAOImpl(this.dbcon.getConnection());//dao接口的子类,这里指定是StudentDAOImpl,Spring里可以同xml解析
	}
	
	//1.插入数据
	public boolean doCreate(Student stu) throws Exception 
	{
		boolean flag = false;
		
		try
		{
			if(null == this.dao.findById(stu.getStudentid()))//查主键,看看是否已经存在
			{
				flag = this.dao.doCreate(stu);//根据dao的子类(StudentDAOImpl),插入数据
			}
		}catch(Exception e){
			throw e;
		}finally{
			this.dbcon.close();//无论如何数据库都应该关闭
		}
		
		return flag;
	}

	//2.按String查找可重复的非主键
	public List<Student> findAll(String keyword) throws Exception 
	{	
		List<Student> all = null;
		try
		{
			all = this.dao.findAll(keyword);//根据dao的子类(StudentDAOImpl),查询
		}catch(Exception e){
			throw e;
		}finally{
			this.dbcon.close();//无论如何数据库都应该关闭
		}
		return all;
	}

	//3.按int查找主键
	public Student findById(int stuNo) throws Exception 
	{
		Student stu = null;
		try
		{
			stu = this.dao.findById(stuNo);//根据dao的子类(StudentDAOImpl),查询
		}catch(Exception e){
			throw e;
		}finally{
			this.dbcon.close();//无论如何数据库都应该关闭
		}
		return stu;
	}

}



4.具体指定连接到哪个数据库(DBConnection.java):

    代理类构造函数中指定的连接方法,如果代理的构造换掉,就能实现连接不同数据库。

package com.rt.daodemo.dao;

import java.sql.Connection;
import java.sql.DriverManager;

public class DBConnection 
{
    private static final String DBDriver = "oracle.jdbc.driver.OracleDriver";//驱动    
    private static final String DBURL = "jdbc:oracle:thin:@localhost:1521:ORCL";//URL命名规则:jdbc:oracle:thin:@IP地址:端口号:数据库实例名     
    private static final String DBUser = "scott";  
    private static final String DBPassWord = "890307"; 
    Connection con = null;  
    
    public DBConnection() throws Exception
    {
    	 Class.forName(DBDriver);//加载数据库驱动    
    	 con = DriverManager.getConnection(DBURL, DBUser, DBPassWord);//连接    
         System.out.println("已连接 "+con);  	 
    }
    public Connection getConnection()
    {
    	return this.con;
    }
    public void close() throws Exception
    {
    	if(null != this.con)
    	{	
    		this.con.close();
    	}
    }
	
    
}



5.其中一种具体实现( StudentDAOImpl.java ):

    连接数据库成功后,就把Student对象存进去。

    这就是上边代理类指定的Student对象的具体实现,这才是具体的业务,这出现了如何把Student对象通过SLQ存到已连接好的数据库里

package com.rt.daodemo.dao.impl;

import java.util.ArrayList;
import java.util.List;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import com.rt.daodemo.model.Student;//引入VO
import com.rt.daodemo.dao.IStudentDAO;//引入接口
//实现类,继承于接口类
//数据库连接交给代理类完成
public class StudentDAOImpl implements IStudentDAO 
{
	private Connection conn = null;
	private PreparedStatement pstmt = null;
	
	public StudentDAOImpl(Connection con)//构造
	{
		this.conn = con;
	}
	
	//1.插入数据
	public boolean doCreate(Student stu) throws Exception 
	{
		boolean flag = false;
		String sql = "INSERT INTO student(studentid,name,age) VALUES(?,?,?)";
		this.pstmt = this.conn.prepareStatement(sql);//组装sql语句
		
		this.pstmt.setInt(1, stu.getStudentid());//从VO传来的值
		this.pstmt.setString(2, stu.getName());
		this.pstmt.setInt(3, stu.getAge());
		
		if(this.pstmt.executeUpdate() > 0)
		{
			flag = true;//如果返回值大于0,表示更新成功了
		}
		this.pstmt.close();
		
		return flag;
	}

	//2.按String查找可重复的非主键
	public List<Student> findAll(String keyword) throws Exception 
	{	
		List<Student> all = new ArrayList<Student>();//查询结果的list
		String sql = "SELECT studentid,name,age FROM student WHERE name LIKE ? ";
		this.pstmt = this.conn.prepareStatement(sql);//组装查询sql语句
		this.pstmt.setString(1, "%"+ keyword +"%");

		ResultSet rs = this.pstmt.executeQuery();//sql的结果集
		Student stu = null;
		while(rs.next())//循环赋值
		{
			stu = new Student();
			stu.setStudentid(rs.getInt(1));
			stu.setName(rs.getString(2));
			stu.setAge(rs.getInt(3));
			
			all.add(stu);//加到List中
		}
		
		this.pstmt.close();//关闭
		return all;
	}

	//3.按int查找主键
	public Student findById(int stuNo) throws Exception 
	{
		Student stu = null;
		String sql = "SELECT studentid,name,age FROM student WHERE studentid LIKE ?";
		this.pstmt = this.conn.prepareStatement(sql);//组装查询sql语句
		this.pstmt.setInt(1,stuNo);

		ResultSet rs = this.pstmt.executeQuery();//sql的结果集
		while(rs.next())
		{
			stu = new Student();
			stu.setStudentid(rs.getInt(1));
			stu.setName(rs.getString(2));
			stu.setAge(rs.getInt(3));
		}
		
		this.pstmt.close();//关闭
		return stu;
	}

}


接口在此:
package com.rt.daodemo.dao;
import java.util.List;
import com.rt.daodemo.model.*;//导入VO

public interface IStudentDAO //方法接口,I开头代表interface
{
	public boolean doCreate(Student stu) throws Exception;
	public List<Student> findAll(String keyword) throws Exception;
	public Student findById(int stuNo) throws Exception;
}



6.最后是VO(Student.java):

这个就没什么好说的了

package com.rt.daodemo.model;

public class Student //VO存储表中所对应的属性
{
	private int studentid;
	private String name;
	private int age;
	
	//setter&getter
	public int getStudentid() {
		return studentid;
	}
	public void setStudentid(int studentid) {
		this.studentid = studentid;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	
}

建表时和VO对应就行了

DROP TABLE student;  
CREATE TABLE student    
(    
    studentid NUMBER(9),    
    name VARCHAR2(50) NOT NULL,    
    age NUMBER(9) NOT NULL,    
    CONSTRAINT student_studentid_pk PRIMARY KEY(studentid)     
); 



    下一步是根据这个小例子,把框架整合进来,下回分解。










  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值