`
guanjh
  • 浏览: 229162 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

Spring的DAO入门

    博客分类:
  • Java
阅读更多

 

 传统的DAO模式

<!--[if !vml]--><!--[endif]-->
Figure 1. Application structure, before and after DAO

设计一个接口

IEmployeeDAO.java

import java.util.Map;

public interface IEmployeeDAO {
  //SQL String that will be executed
  public String FIND_BY_SAL_RNG = "SELECT EMP_NO, EMP_NAME, "
  + "SALARY FROM EMP WHERE SALARY >= ? AND SALARY <= ?";

  //Returns the list of employees who fall into the given salary
  //range. The input parameter is the immutable map object
  //obtained from the HttpServletRequest. This is an early
  //refactoring based on "Introduce Parameter Object"

  public List findBySalaryRange(Map salaryMap);
}

实现这个接口

IEmployeeDAO.java

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import com.bea.dev2dev.to.EmployeeTO;

public class EmployeeDAOImpl implements IEmployeeDAO{

  public List findBySalaryRange(Map salaryMap)
  {
    Connection conn = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    List empList = new ArrayList();
    //Transfer Object for inter-tier data transfer
    EmployeeTO tempEmpTO = null;
    try{
    //DBUtil - helper classes that retrieve connection from pool
      conn = DBUtil.getConnection();
      pstmt = conn.prepareStatement(FIND_BY_SAL_RNG);
      pstmt.setDouble(1, Double.valueOf( (String)
          salaryMap.get("MIN_SALARY") );
      pstmt.setDouble(2, Double.valueOf( (String)
          salaryMap.get("MIN_SALARY") );
      rs = pstmt.executeQuery();
      int tmpEmpNo = 0;
      String tmpEmpName = "";
      double tmpSalary = 0.0D;
      while (rs.next()){
        tmpEmpNo = rs.getInt("EMP_NO");
        tmpEmpName = rs.getString("EMP_NAME");
        tmpSalary = rs.getDouble("SALARY");
        tempEmpTO = new EmployeeTO(tmpEmpNo,
              tmpEmpName,
              tmpSalary);
        empList.add(tempEmpTO);  
      }//end while
    }//end try
    catch (SQLException sqle){
      throw new DBException(sqle);
    }//end catch
    finally{
      try{
        if (rs != null){
          rs.close();
        }
      }
      catch (SQLException sqle){
        throw new DBException(sqle);
      }
      try{
        if (pstmt != null){
          pstmt.close();
        }       
      }
      catch (SQLException sqle){
        throw new DBException(sqle);
      }
      try{
        if (conn != null){
          conn.close();
        }       
      }
      catch (SQLException sqle){
        throw new DBException(sqle);
      }
    }//end of finally block
    return empList;
  }//end method findBySalaryRange
}

 

以上说明了DAO几个关键点:

  • They encapsulate all interactions with the JDBC API. If an O/R mapping solution like Kodo or Hibernate were being used, the DAO classes can wrap the proprietary APIs of these products.
  • They wrap the retrieved data in a JDBC API-neutral transfer object and returns it to the business tier for further processing.
  • They are stateless in nature. Their sole aim is to access and change persistent data for the business objects.
  • They trap any errors (for example, database is unavailable, wrong SQL syntax) reported in the process by the underlying JDBC API or database as SQLException. The DAO objects notify the business objects of such errors again by a JDBC-neutral, custom build runtime exception class DBException.
  • They release database resources like Connection and PreparedStatement objects back to the pool and relinquish memory held by ResultSet cursors after they have been used.

 

Therefore, the DAO layer provides a consistent data access API for the business tier abstracting the low level data access API.

生成DAO Factory

DAOFactory.java

public class DAOFactory {
  private static DAOFactory daoFac;

  static{
    daoFac = new DAOFactory();
  }

  private DAOFactory(){}

  public DAOFactory getInstance(){
    return daoFac;
  }

  public IEmployeeDAO getEmployeeDAO(){
    return new EmployeeDAOImpl();
  }
}

business组件结合

EmployeeBusinessServiceImpl .java

public class EmployeeBusinessServiceImpl implements
                                       IEmployeeBusinessService {

  public List getEmployeesWithinSalaryRange(Map salaryMap){

    IEmployeeDAO empDAO = DAOFactory.getInstance()
                                    .getEmployeeDAO();
    List empList = empDAO.findBySalaryRange(salaryMap);
    return empList;
  }
}

 

问题:

The DAO design pattern is not devoid of shortcomings:

  • Code Repetition: As evident from the EmployeeDAOImpl listing, code repetition (shown in bold above) is a major problem with JDBC-based, traditional database access. Writing boilerplate code over and over is a clear violation of the basic OO principle of code reuse. This has obvious side effects in terms of project cost, timelines, and effort.
  • Coupling: The DAO code is very tightly coupled with the JDBC interfaces and core collections. This is evident from the number of import statements per DAO class.
  • Resource Leakage: Following the design of the EmployeeDAOImpl class, all DAO methods must relinquish control of acquired database resources like connection, statements, and result sets. This is a risky proposition because a novice programmer can very easily skip those bits. As a result, resources would run out and bring the system to a halt.
  • Error Handling: JDBC drivers report all error situations by raising the SQLException. SQLException is a checked exception, therefore developers are forced to handle it—even though it isn't possible to recover from the majority of these exceptions, which results in cluttering the code. Moreover, the error code and message obtained from the SQLException object are database vendor-specific, so it's not possible to write portable DAO error messaging code.
  • Fragile Code: The setting of the bind variables for the statement object, and the retrieval of the data using the result set getter methods are two frequently used tasks in JDBC-based DAO. If the number of columns in the SQL where clause is changed, or the column positions are altered, the code has to go through the rigorous cycle of change, test, and redeployment.

进入Spring DAO


Figure 2. Major components of the Spring JDBC framework

JdbcTemplate 是最重要的 类,使用它能避免很过 错误,它主要做了以下工作:

  • Retrieves connections from the datasource.
  • Prepares appropriate statement object.
  • Executes SQL CRUD operations.
  • Iterates over result sets and populates the results in standard collection objects.
  • Handles SQLException exceptions and translates them to a more error-specific exception hierarchy.
  • 用Spring DAO重写

    分享到:
    评论

    相关推荐

      Spring DAO入门实例

      Spring DAO入门实例入门实例DOC,经典入门

      Spring轻松入门教程

      Spring轻松入门教程你将会创建一个简单的程序完成最基本的CRUD(Create,Retrieve,Update和Delete)操作。这个程序 叫MyUsers,作为本书的样例。这是一个三层架构的web程序,通过一个Action来调用业务委派, 再通过它...

      Spring 快速入门教程

      学习用struts MVC框架作前端,Spring做中间层,Hibernate作后端来开发一个 简单的Spring应用程序。在第4章将使用Spring MVC框架对它进行...设置业务代理(business delegates)和DAO的依赖性。 把spring写入Struts 程序。

      spring data jpa入门实例

      spring Data家族给我们提供了一个现成的dao层框架,这里面有不同的项目,如Spring Data JPA, Spring Data Neo4j and Spring Data MongoDB,他们的共同特点是他们给我们提供了框架代码,不再需要我们自己去实现了。

      Java spring快速入门,附源码和学习资料仅供学习,使用IDEA工具

      1、Spring程序开发步骤;...3、编写Dao接口和实现类; 4、 创建Spring核心配置文件; 5、在Spring配置文件中配置UserDaoImpl; 6、 使用Spring的API获得Bean实例; 7、 Spring配置文件; 8、Bean的依赖注入入门; 等等

      Spring快速入门教程

      编写功能性测试。 配置Hibernate和Transaction。 载入Spring的applicationContext.xml文件。 设置业务代理(business delegates)和DAO的依赖性。 把spring写入Struts 程序。

      spring快速入门教程

      编写功能性测试。 配置Hibernate和Transaction。 载入Spring的applicationContext.xml文件。...设置业务代理(business delegates)和DAO的依赖性。 把spring写入Struts 程序。 如何结合Hibernate和Struts

      Myeclipse开发struts+hibernate+spring新手入门--环境配置---项目开发示例

      Myeclipse开发struts+hibernate+spring新手入门---环境配置----项目开发示例 Myeclipse开发struts+hibernate+spring小记 开发前准备工作: 1、下载eclipse3.1版本 下载地址: 2、下载Myeclipse插件 下载地址: 3...

      Struts+Spring+Hibernate快速入门

      本文是开发基于spring的web应用的入门文章,前端采用Struts MVC框架,中间层采用spring,后台采用Hibernate。  本文包含以下内容:  •配置Hibernate和事务  •装载Spring的applicationContext.xml文件  •...

      Spring初学入门

      本人使用Spring开发能有1年了,从最初简单使用Spring的DAO到现在的AOP等相关其他功能,深深感到Spring给开发者带来的惊喜和便利。故此,在从网上下载到《Spring Live》的英文原版后,下决心要把它翻译出来。由于本人...

      SpringCloud入门.docx

      (2)将原先写在同一个模块下的service,dao,controller等等分别拆分到不同的Maven模块下。 (3)使用maven进行install安装到本地仓库 (4)引入模块依赖进行使用 3.依赖传递:依赖具有传递性,在不同模块重复依赖会有...

      Spring Framework 5 中文文档

      1. 入门指南 2. 介绍Spring框架 3. IoC容器 4. 资源 5. 验证、数据绑定和类型转换 6. Spring表达式语言 9. Spring框架下的测试 10. 单元测试 11. 集成测试 14. DAO支持 15.使用JDBC实现数据访问 16. ORM和数据访问 ...

      SSM框架教程Spring+SpringMVC+MyBatis全覆盖_Java热门框架视频教程

      1、Spring简介及快速入门 2、Spring配置文件及其相应API 3、Spring注解开发 4、Spring web环境及其Junit的集成 5、Spring JDBCTemplate的基本使用 6、Spring AOP的介绍及其配置使用 7、Spring的声明式事务控制 8、...

      Spring+SpringMVC+MyBatis入门必备

      Spring+SpringMVC+mybatist三大框架整合项目,java代码分为 dao,service,controller三层,支持注 解,事务。数据库默认MySQL,配置文件为src下的config资源包中的 db.properties,以KEY VALUE形式保存数据库连接属性...

      JavaEE技术-试验九.zip_Spring入门_依赖注入

      在MyEclipse环境下运用Spring的依赖注入技术,实现service层和dao层的解耦合。运用hibernate框架完成相应的数据库添加和查询功能

      《精通Spring2.X企业应用开发详解》随书源码1-15章

      Spring容器高级主题 第6章 Spring AOP基础 第7章 基于@AspectJ和Schema的 第7章 AOP 第3篇 数据库访问 第8章 Spring对DAO的支持 第9章 Spring的事务管理 第10章 使用Spring JDBC访问数据库 ...

      Java后端开发-Spring库.zip

      一、Spring入门程序 1.创建项目,Spring依赖包。 2.创建JavaBean:HelloSpring 3.编写applicationContext.xml配置文件 4.测试:启动Spring,获取Hello示例。 二、Spring基于XML装配实验 说明:使用Spring IOC模拟...

      开源框架 Spring Gossip

      Spring MVC 入门 从一个最简单的 Spring Web 应用程式,来看看 Spring MVC 框架的架构与 API 组成元素。 第一个 Spring MVC 程式 WebApplicationContext Handler Mapping Handler ...

      Spring 5 英文文档全套.7z

      历史,设计理念,反馈,入门。 核心 IoC容器,事件,资源,i18n,验证,数据绑定,类型转换,SpEL,AOP。 测试 模拟对象,TestContext框架,Spring MVC测试,WebTestClient。 资料存取 事务,DAO支持,JDBC,O / ...

    Global site tag (gtag.js) - Google Analytics