JAVA DAO

DAO的组成  
 1.实体  
    一个java类,这个类与数据库中的表对应。  
    比如,table_user表与User类对应:  
    对应关系指的是:  
    table_user表名与User类名对应  
    table_user表的列(column)与User类的属性对应  

    table_user表中的一条记录与User类的一个实例对应  

2.数据库

   数据库的创建,链接。

3.dao接口  
   声明一系列方法(即对数据库进行哪些操作--crud),  
   这些方法应该与具体的技术无关。  
 3.dao实现  

   实现dao接口的一个具体类DaoImpl  

4.dao的代理

   对象访问的管理

 5.工厂  
   提供符合接口定义的对象,调用者不用关心对象的创建细节。  

   也就是说,通过工厂,可以将调用者与要调用的对象解耦了。 

显示层->DAO.HTML:

<html>
<head><title>DAO</title></head>
<body>
	<form action="createEmp.jsp" method="post">
		<table>
			<tr>
				<td>用户名:</td>
				<td><input  type="text" name="user" width="20px"/></td>
			</tr>
			<tr>
				<td>密码:</td>
				<td><input  type="password" name="password"/></td>
			</tr>
			<tr>
				<td>邮箱:</td>
				<td><input  type="text" name="email"/></td>
			</tr>
			<tr>
				<td><input type="submit" value=" 注册"/></td>
				<td><input  type="reset" value="重置"/></td>
			</tr>									
		</table>
	</form>
</body>
</html>

控制层->createEmp.jsp

<%@page contentType="text/html" pageEncoding="GBK"%>
<%@page import="DAO.VO.Emp"%>
<html>
<head><title>createEmp</title></head>

<body>
<center>hello</center>
	<jsp:useBean id="emp" class="DAO.VO.Emp" />
	<jsp:useBean id="factory" class="DAO.Factory.EmpDAOFactory" />
	<%
		String user  = request.getParameter("user");
		String pass  = request.getParameter("password");
		String email = request.getParameter("email");
		emp = new Emp(user,pass,email);
		/*emp.setUser(user);
		emp.setPassword(pass);
		emp.setEmail(email);*/
		factory.instance().createEmp(emp);
	%>
	
	<%="user->"+user%><br />
	<%="pass->"+pass%><br />
	<%="email->"+email%><br />
</body>
</html>

实体VO->emp.java:

package DAO.VO;
public class Emp
{
	private int id;
	private String user;
	private String password;
	private String email;
	public Emp(){

	}
	public Emp(String user,String password,String email){
		this.user = user;
		this.password = password;
		this.email = email;
	}
	public Emp(int id,String user,String password,String email){
		this.id = id;
		this.user = user;
		this.password = password;
		this.email = email;
	}
	public void setID(int id){
		this.id = id;
	}
	public void setUser(String user){
		this.user = user;
	}
	public void setPassword(String password){
		this.password = password;
	}
	public void setEmail(String email){
		this.email = email;
	}
	public int getID(){
		return this.id;
	}
	public String getUser(){
		return user;
	}
	public String getPassword(){
		return password;
	}
	public String getEmail(){
		return email;
	}
	/*public static void main(String[] args){
		Emp e = new Emp();
		e.setID(2);
		e.setUser("hua");
		e.setPassword("aaaaa.0");
		e.setEmail("980914629@qq.com");
		println("ID:"+e.getID());
		println("User:"+e.getUser());
		println("Password:"+e.getPassword());
		println("Email:"+e.getEmail());
	}
	public static void println(Object obj){
		System.out.println(obj);
	}*/

}

数据库->DatabaseConnection.java:

package DAO.DBC;
import java.sql.*;
public class DatabaseConnection 
{
	private static final String DRIVER     = "org.gjt.mm.mysql.Driver";
	private static final String DBURL      = "jdbc:mysql://localhost:3306/emp";
	private static final String DBUSER	   = "scott";
	private static final String DBPASSWORD = "tiger";
	private static Connection conn;
	public DatabaseConnection()throws Exception{
		Class.forName(DRIVER);//驱动加载
		conn = DriverManager.getConnection(DBURL,DBUSER,DBPASSWORD);//连接数据库
	}
	public Connection getConnection(){
		return conn;
	}
	public void close()throws Exception{
		conn.close();
	}
	/*public static void main(String[] args)throws Exception 
	{
		DatabaseConnection dc = new DatabaseConnection();
		dc.connection();
		printf(dc.getConnection());

		Connection conn  = dc.getConnection();
		Statement state  = conn.createStatement();
		state.executeUpdate("use study");//首先要使用哪个数据库
		ResultSet result = state.executeQuery("select * from emp");
		while(result.next()){
			printf(result.getObject("id"));
			printf(result.getObject("user"));
			printf(result.getObject("password"));
			printf(result.getObject("email"));
		}

		dc.close();
	}
	public static void printf(Object obj){
		System.out.println(obj);
	}*/
}

DAO接口->IEmpDAO.java:

package DAO.IEmpDAO;
import  DAO.VO.*;
import java.util.*;
public interface IEmpDAO
{
	public boolean createEmp(Emp emp)throws Exception;
	public List<Emp> findAll(String keyWord)throws Exception;
	public Emp findByID(int id)throws Exception;
}

DAO实现类->EmpDAOImpl.java:

package DAO.EmpDAOImpl;
import DAO.VO.*;
import DAO.IEmpDAO.*;
import java.util.*;
import java.sql.*;
public class  EmpDAOImpl implements IEmpDAO 
{
	private Connection conn;
	PreparedStatement preStatement;
	ResultSet result;
	public EmpDAOImpl(Connection conn){		
		preStatement = null;
		result = null;
		this.conn = conn;
	}
	public boolean createEmp(Emp e)throws Exception{						
		
		preStatement = conn.prepareStatement("INSERT INTO emp(user,password,email) VALUES(?,?,?)");
		preStatement.setString(1,e.getUser());
		preStatement.setString(2,e.getPassword());
		preStatement.setString(3,e.getEmail());
		preStatement.execute("use study");//先使用哪个数据库
		preStatement.execute();		
		preStatement.close();		
		return true;
	}
	public List<Emp> findAll(String keyWord)throws Exception{
		List <Emp> emps = new ArrayList<Emp>();
		preStatement = conn.prepareStatement("select * from emp where user like ? or password like ?");
		preStatement.setString(1,"%"+keyWord+"%");
		preStatement.setString(2,"%"+keyWord+"%");
		preStatement.execute("use study");//先使用哪个数据库
		result = preStatement.executeQuery();
		while(result.next()){
			Emp emp = new Emp(result.getInt("id"),
							  result.getString("user"),
				              result.getString("password"),
							  result.getString("email")
							  );
			emps.add(emp);
			}		
		preStatement.close();
		return emps;
	}
	public Emp findByID(int id)throws Exception{	
		Emp emp = null;
		preStatement = conn.prepareStatement("select * from emp where id=?");
		preStatement.setInt(1,id);
		result = preStatement.executeQuery();
		while(result.next()){
			emp = new Emp(result.getInt("id"),
						  result.getString("user"),
						  result.getString("password"),
						  result.getString("email")
						);
		}
		preStatement.close();
		return emp;
	}
	public boolean findEmp(String user)throws Exception{
		List <Emp> emps = new ArrayList<Emp>();
		preStatement = conn.prepareStatement("select * from emp where user=?");
		preStatement.setString(1,user);		
		preStatement.execute("use study");
		result = preStatement.executeQuery();
		while(result.next()){		
			 String userTemp = result.getString("user");
			 if(user.equals(userTemp)){
				preStatement.close();
				return true;
			 }
			}		
		preStatement.close();
		return false;
	}
	/*public static void main(String[] args)throws Exception{
		EmpDAOImpl edi = new EmpDAOImpl(new DatabaseConnection().getConnection());
		edi.createEmp(new Emp("hua1","aaaaa.0","435501646@qq.com"));

		List <Emp> emps = edi.findAll("hu");
		for(int i=0;i<emps.size();i++){
			printf(emps.get(i).getID()+" ");
			printf(emps.get(i).getUser()+" ");
			printf(emps.get(i).getPassword()+" ");
			printfln(emps.get(i).getEmail());
		}

		Emp emp;
		emp = edi.findByID(5);
		printf(emp.getID()+" ");
		printf(emp.getUser()+" ");
		printf(emp.getPassword()+" ");
		printfln(emp.getEmail());
	}
	public static void printf(Object obj){
		System.out.print(obj);
	}
	public static void printfln(Object obj){
		System.out.println(obj);
	}*/
}

DAO代理->EmpDAOProxy.java:

package DAO.EmpProxy;
import DAO.VO.*;
import DAO.IEmpDAO.*;
import DAO.DBC.*;
import DAO.EmpDAOImpl.*;
import java.util.*;
public class EmpDAOProxy implements IEmpDAO
{
	private DatabaseConnection dc;
	private EmpDAOImpl edi;
	public EmpDAOProxy()throws Exception{
		dc  = new DatabaseConnection();
		edi = new EmpDAOImpl(dc.getConnection());	
	}
	public boolean createEmp(Emp emp){		
		try
		{			
			if(!edi.findEmp(emp.getUser()))
				edi.createEmp(emp);	
			else
				return false;
		}
		catch (Exception e)
		{
			
		}
		finally
		{
			try
			{
				dc.close();	
			}
			catch (Exception e)
			{
			}			
		}				
		return true;
	}
	public List<Emp> findAll(String keyWord){
		List<Emp> emps = new ArrayList<Emp>();
		try
		{
			emps = edi.findAll(keyWord);
		}
		catch (Exception e)
		{
		}
		return emps;
	}
	public Emp findByID(int id){
		Emp emp = null;
		try
		{
			emp = edi.findByID(id);
		}
		catch (Exception e)
		{
		}
		return emp;
	}
	/*public static void main(String[] args){
		System.out.println("Hello World!");
	}*/
	public static void printf(Object obj){
		System.out.print(obj);
	}
	public static void printfln(Object obj){
		System.out.println(obj);
	}
}

DAO工厂->EmpDAOFactory.java:

package DAO.Factory;
import DAO.VO.*;
import DAO.EmpProxy.*;
public class EmpDAOFactory 
{
	public static EmpDAOProxy instance()throws Exception{
		return new EmpDAOProxy();
	}
}

      我觉得对于初学者,如果是为了测试一下这种的设计模式,最后一步一步来,免得出麻烦,搞到头都大,像我那些注释的那样,

都是一步一步来的,虽然可能有点慢,但是自己会更加注意那些细节,而且如果一下子写完的话,如果出错了,那时候头就大了,

不要看到那些代码都是一下子出现你面前,你就要一下子写完它,应该理解之后,再一步一步慢慢写,这样才能有好的收获的。



<pre name="code" class="java"><pre name="code" class="java"><pre name="code" class="java"><pre name="code" class="java"><pre name="code" class="java"><pre>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

                
工厂模式定义:提供创建对象的接口. 为何使用? 工厂模式是我们最常用的模式了,著名的Jive论坛 ,就大量使用了工厂模式,工厂模式在Java程序系统可以说是随处可见。 为什么工厂模式是如此常用?因为工厂模式就相当于创建实例对象的new,我们经常要根据类Class生成实例对象,如A a=new A() 工厂模式也是用来创建实例对象的,所以以后new时就要多个心眼,是否可以考虑实用工厂模式,虽然这样做,可能多做一些工作,但会给你系统带来更大的可扩展性和尽量少的修改量。 我们以类Sample为例, 如果我们要创建Sample的实例对象: Sample sample=new Sample(); 可是,实际情况是,通常我们都要在创建sample实例时做点初始化的工作,比如赋值 查询数据库等。 首先,我们想到的是,可以使用Sample的构造函数,这样生成实例就写成: Sample sample=new Sample(参数); 但是,如果创建sample实例时所做的初始化工作不是象赋值这样简单的事,可能是很长一段代码,如果也写入构造函数中,那你的代码很难看了(就需要Refactor重整)。 为什么说代码很难看,初学者可能没有这种感觉,我们分析如下,初始化工作如果是很长一段代码,说明要做的工作很多,将很多工作装入一个方法中,相当于将很多鸡蛋放在一个篮子里,是很危险的,这也是有背于Java面向对象的原则,面向对象的封装(Encapsulation)和分派(Delegation)告诉我们,尽量将长的代码分派“切割”成每段,将每段再“封装”起来(减少段和段之间偶合联系性),这样,就会将风险分散,以后如果需要修改,只要更改每段,不会再发生牵一动百的事情。 在本例中,首先,我们需要将创建实例的工作与使用实例的工作分开, 也就是说,让创建实例所需要的大量初始化工作从Sample的构造函数中分离出去。 这时我们就需要Factory工厂模式来生成对象了,不能再用上面简单new Sample(参数)。还有,如果Sample有个继承如MySample, 按照面向接口编程,我们需要将Sample抽象成一个接口.现在Sample是接口,有两个子类MySample 和HisSample .我们要实例化他们时,如下: Sample mysample=new MySample(); Sample hissample=new HisSample(); 随着项目的深入,Sample可能还会"生出很多儿子出来", 那么我们要对这些儿子一个个实例化,更糟糕的是,可能还要对以前的代码进行修改:加入后来生出儿子的实例.这在传统程序中是无法避免的. 但如果你一开始就有意识使用了工厂模式,这些麻烦就没有了. 工厂方法 你会建立一个专门生产Sample实例的工厂: public class Factory{   public static Sample creator(int which){   //getClass 产生Sample 一般可使用动态类装载装入类。   if (which==1)     return new SampleA();   else if (which==2)     return new SampleB();   } } 那么在你的程序中,如果要实例化Sample时.就使用 Sample sampleA=Factory.creator(1); 这样,在整个就不涉及到Sample的具体子类,达到封装效果,也就减少错误修改的机会,这个原理可以用很通俗的话来比喻:就是具体事情做得越多,越容易范错误.这每个做过具体工作的人都深有体会,相反,官做得越高,说出的话越抽象越笼统,范错误可能性就越少.好象我们从编程序中也能悟出人生道理?呵呵. 使用工厂方法 要注意几个角色,首先你要定义产品接口,如上面的Sample,产品接口下有Sample接口的实现类,如SampleA,其次要有一个factory类,用来生成产品Sample,如下图,最右边是生产的对象Sample: 进一步稍微复杂一点,就是在工厂类上进行拓展,工厂类也有继承它的实现类concreteFactory了。 抽象工厂 工厂模式中有: 工厂方法(Factory Method) 抽象工厂(Abstract Factory). 这两个模式区别在于需要创建对象的复杂程度上。如果我们创建对象的方法变得复杂了,如上面工厂方法中是创建一个对象Sample,如果我们还有新的产品接口Sample2. 这里假设:Sample有两个concrete类SampleA和SamleB,而Sample2也有两个concrete类Sample2A和SampleB2 那么,我们就将上例中Factory变成抽象类,将共同部分封装在抽象类中,不同部分使用子类实现,下面就是将上例中的Factory拓展成抽象工厂: public abstract class Factory{   public abstract Sample creator();   public abstract Sample2 creator(String name); } public class SimpleFactory extends Factory{   public Sample creator(){     .........     return new SampleA   }   public Sample2 creator(String name){     .........     return new Sample2A   } } public class BombFactory extends Factory{   public Sample creator(){     ......     return new SampleB   }   public Sample2 creator(String name){     ......     return new Sample2B   } } 从上面看到两个工厂各自生产出一套Sample和Sample2,也许你会疑问,为什么我不可以使用两个工厂方法来分别生产Sample和Sample2? 抽象工厂还有另外一个关键要点,是因为 SimpleFactory内,生产Sample和生产Sample2的方法之间有一定联系,所以才要将这两个方法捆绑在一个类中,这个工厂类有其本身特征,也许制造过程是统一的,比如:制造工艺比较简单,所以名称叫SimpleFactory。 在实际应用中,工厂方法用得比较多一些,而且是和动态类装入器组合在一起应用, 举例 我们以Jive的ForumFactory为例,这个例子在前面的Singleton模式中我们讨论过,现在再讨论其工厂模式: public abstract class ForumFactory {   private static Object initLock = new Object();   private static String className = "com.jivesoftware.forum.database.DbForumFactory";   private static ForumFactory factory = null;   public static ForumFactory getInstance(Authorization authorization) {     //If no valid authorization passed in, return null.     if (authorization == null) {       return null;     }     //以下使用了Singleton 单态模式     if (factory == null) {       synchronized(initLock) {         if (factory == null) {             ......           try {               //动态转载类               Class c = Class.forName(className);               factory = (ForumFactory)c.newInstance();           }           catch (Exception e) {               return null;           }         }       }     }     //Now, 返回 proxy.用来限制授权对forum的访问     return new ForumFactoryProxy(authorization, factory,                     factory.getPermissions(authorization));   }   //真正创建forum的方法由继承forumfactory的子类去完成.   public abstract Forum createForum(String name, String description)   throws UnauthorizedException, ForumAlreadyExistsException;   .... } 因为现在的Jive是通过数据库系统存放论坛帖子等内容数据,如果希望更改为通过文件系统实现,这个工厂方法ForumFactory就提供了提供动态接口: private static String className = "com.jivesoftware.forum.database.DbForumFactory"; 你可以使用自己开发的创建forum的方法代替com.jivesoftware.forum.database.DbForumFactory就可以. 在上面的一段代码中一共用了三种模式,除了工厂模式外,还有Singleton单态模式,以及proxy模式,proxy模式主要用来授权用户对forum的访问,因为访问forum有两种人:一个是注册用户 一个是游客guest,那么那么相应的权限就不一样,而且这个权限是贯穿整个系统的,因此建立一个proxy,类似网关的概念,可以很好的达到这个效果. 看看Java宠物店中的CatalogDAOFactory: public class CatalogDAOFactory {   /**   * 本方法制定一个特别的子类来实现DAO模式。   * 具体子类定义是在J2EE的部署描述器中。   */   public static CatalogDAO getDAO() throws CatalogDAOSysException {     CatalogDAO catDao = null;     try {       InitialContext ic = new InitialContext();       //动态装入CATALOG_DAO_CLASS       //可以定义自己的CATALOG_DAO_CLASS,从而在无需变更太多代码       //的前提下,完成系统的巨大变更。       String className =(String) ic.lookup(JNDINames.CATALOG_DAO_CLASS);       catDao = (CatalogDAO) Class.forName(className).newInstance();     } catch (NamingException ne) {       throw new CatalogDAOSysException("         CatalogDAOFactory.getDAO: NamingException while           getting DAO type : \\n" + ne.getMessage());     } catch (Exception se) {       throw new CatalogDAOSysException("         CatalogDAOFactory.getDAO: Exception while getting           DAO type : \\n" + se.getMessage());     }     return catDao;   } } CatalogDAOFactory是典型的工厂方法,catDao是通过动态类装入器className获得CatalogDAOFactory具体实现子类,这个实现子类在Java宠物店是用来操作catalog数据库,用户可以根据数据库的类型不同,定制自己的具体实现子类,将自己的子类名给与CATALOG_DAO_CLASS变量就可以。 由此可见,工厂方法确实为系统结构提供了非常灵活强大的动态扩展机制,只要我们更换一下具体的工厂方法,系统其他地方无需一点变换,就有可能将系统功能进行改头换面的变化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值