实现可扩展的DAO,本文给出实现DAO的编程思想。

2024-05-01 05:58

本文主要是介绍实现可扩展的DAO,本文给出实现DAO的编程思想。,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

开发环境:本文使用TomcatStrutsMySQL

为实现可扩展的DAO,本文将使用JNDI连接数据库,并将JNDI保存在XML文件里。同时也将调用sql语句的类 名保存在XML文件里。

例如:

1 dao-config.xml。该文件可以配置多个数据库的JNDI。在DAO初始化时,会将这些信息存入对象里。JNDI名为java:comp/env/jdbc/Colimas

<!--DOCTYPE dao SYSTEM "/DTD/dao.dtd"-->

<dao>

        <dao-config id="base" type="jdbc">

                <dao-param name="datasource">java:comp/env/jdbc/Colimas</dao-param>

        </dao-config>     

</dao>

2 dao-declaration.xml。该文件保存处理某数据库表的类名。

<dao>

        <dao-object name="daoCBI">

                <use-dao id="base"/>

                <class>com.nova.colimas.data.sql.SQLTCBI</class>

        </dao-object>

        <dao-object name="daoUBI">

                <use-dao id="base"/>

                <class>com.nova.colimas.data.sql.SQLTUBI</class>

        </dao-object>     

                <dao-object name="daoURM">

                <use-dao id="base"/>

                <class>com.nova.colimas.data.sql.SQLTURM</class>

        </dao-object>    

</dao>

3 配置JNDI。修改Tomcatserver.xml。在<host..><Context..>里面添加

             <Resource name="jdbc/Colimas" auth="Container" type="javax.sql.DataSource"

               maxActive="100" maxIdle="30" maxWait="10000"

               username="root" password="197913" driverClassName="com.mysql.jdbc.Driver"   url="jdbc:mysql://localhost:3306/Colimas?autoReconnect=true"/>

网上的很多文章的JNDI配置方法都不一样。这个对MySQL 5.0的配置方法。另外要到www.mysql.com 里下载最新的jdbc driver: mysql-connector-java-3.1.10-bin.jar

拷贝到$(TOMCATHOME)/common/lib

4 配置web.xml。在你的web app里调用jndi需要添加

      <resource-ref>

            <description>DB Connection</description>

            <res-ref-name>jdbc/Colimas</res-ref-name>

            <res-type>javax.sql.DataSource</res-type>

            <res-auth>Container</res-auth>

      </resource-ref>

web.xml

5 初始化DAO配置信息。

StartupServlet里装载Dao的配置信息。

public class StartupServlet extends Action {

      /**

       * List of DAO files

       */

      public final static String PARAM_DAO = "dao";

 

 

      public ActionForward execute(ActionMapping mapping,

                   ActionForm form,

                   HttpServletRequest request,

                   HttpServletResponse response)

      throws Exception{

            // Get list of DAO files

            initDAO();

            logger.info("init DAO successfully");          

            return mapping.findForward("success");

      }

 

      /**

       * Initialization of DAO environment

       */

      private void initDAO() throws ServletException

      {

//Constants.DAO的值为两配置文件名:/resources/config/dao-config.xml,/resources/config/dao-declaration.xml

                  StringTokenizer st = new StringTokenizer (Constants.DAO, ",");

                  while (st.hasMoreTokens())

                  {

                        String name = st.nextToken();

                        // Get associated resource

//获得配置文件的URL

                        URL url = getClass().getResource(name);

                        if (url == null)

                        {

                             throw new ServletException ("Cannot find resource for " + name);

                        }

                        else

                        {

                              try

                              {

//使用DAO工厂加载配置文件信息。

                                    DAOFactory.addConfiguration (url);

                              }

                              catch (DAOFactoryException ex)

                              {

                                    throw new ServletException ("Cannot initialize DAO", ex);

                              }

                        }

                  }

      }

}

6 DAO工厂类 DAOFactory

根据输入的dao-object name来实例化DAO对象。

 

 

 

 

 

public abstract class DAOFactory {

      //得到DAOObject

      public static DAOObject getDAOObject(String daoName, DAOContext daoContext) throws DAOFactoryException

      {

            // Gets the DAO object declaration

            // Gets the associated factory

            // Creates DAO object

            return factory.newDAOObject(objectDeclaration);

      }

/**

       * @see com.ibm.services.epricer.framework.dao.DAOFactory#newDAOObject(DAOObjectDeclaration)

       */

      protected DAOObject newDAOObject(DAOObjectDeclaration objectDeclaration) throws DAOFactoryException

      {

            // Gets class

            Class objectClass = (Class) classes.get(objectDeclaration.getName());

            if (objectClass == null)

            {

                  synchronized (classes)

                  {

                        try

                        {

                              objectClass = Class.forName(objectDeclaration.getClassName());

                        }

                        catch (ClassNotFoundException e)

                        {

                              throw new DAOFactoryException (this, "Cannot instantiate the DAO object class " + objectDeclaration.getClassName(), e);

                        }

                        classes.put(objectDeclaration.getName(), objectClass);

                  }

            }

            try

            {

//初始化DAOObject,并将自己传入DAOObject

                  DAOObject object = (DAOObject) objectClass.newInstance();

                  object.init(this);

                  return object;

            }

            catch (Exception ex)

            {

                  throw new DAOFactoryException(this, "Cannot create DAO object " + objectDeclaration.getName(), ex);

            }

      }

 

      /**

       * Add a configuration file for the DAO

       */

      public synchronized static void addConfiguration(URL url) throws DAOFactoryException

      {}

 

}

实现JDBCDAOFactory

 

public class JDBCDAOFactory extends DAOFactory {

      /**

       * Factory parameter, JDBC name of the Data source (example : jdbc/DataSource)

       */

      public final static String PARAM_DATASOURCE = "datasource";

     

      /**

       * JDBC Data Source

       */

      private DataSource dataSource;

 

      private Logger logger;

      /**

       * Initializes the Data source.

       */

      protected void init(Map parameters) throws DAOFactoryException

      {

            logger = Logger.getLogger(this.getClass());

            // Gets the data source name

            String dsName = (String)parameters.get (PARAM_DATASOURCE);

            if (dsName == null)

            {

                  throw new DAOFactoryException (this, "Cannot find 'datasource' parameter to initialize the DAO factory.");

            }

            else

            {

                  try

                  {

                        // JNDI context

                        Context  initialContext = new InitialContext ();

                        // Gets the data source

                        dataSource = (DataSource) initialContext.lookup(dsName);

                       

                  }

                  catch (NamingException ex)

                  {

                        throw new DAOFactoryException (this, "Cannot find JDBC Data Source with JNDI name " + dsName, ex);

                  }

            }

      }

 

      /**

       * Gets a connection from the data source.

       * First, this method try to get the registered connection from the <code>context</code>.

       * If not found, a new connection is created and then registered into the <code>context</code>.

       * @see JDBCDAOSource

       * @param context Current context for DAO accesses

       * @return The DAO source to use (for this factory, it is an instance of <code>JDBCDAOSource</code>

       * @throws DAOFactoryException If the connection cannot be created.

       */

      public DAOSource getDAOSource(DAOContext context) throws DAOFactoryException

      {

            // Gets the DAO source from the context

            DAOSource source = context.getDAOSource(this);

            if (source != null)

            {

                  return source;

            }

            else

            {

                  try

                  {

                        // Creates the connection

                        Connection connection = dataSource.getConnection();

                        connection.setAutoCommit(false);

                        connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);

                        // Creates the DAO source

                        source = new JDBCDAOSource (connection);

                        // Registers it

                        context.setDAOSource(this, source);

                        // Returns it

                        return source;

                  }

                  catch (SQLException ex)

                  {

                        ex.printStackTrace();

                        throw new DAOFactoryException (this, "Cannot get a new connection", ex);

                  }

            }

      }

 

}

其中DAOContext内根据用户的不同保存用户相关的数据库链接。初始时JDBCFactory会建立一个连接然后存入DAOContext中。

 

7 调用DAO Object

      try{

//daoURMDAO Object名称

           SQLTURM urm=(SQLTURM)DAOFactory.getDAOObject(“daoURM”,new  DAOContext(this.userbean,new HashMap()));

           urm.callData(new DAOContext(this.userbean,new HashMap()));

      }catch(DAOException e){

                  logger.error(e);

      }

其中SQLTURMDAOObject

 

public class SQLTURM extends JDBCDAOObject {

      /**

       *

       * @param m_context context may contain projectid

       */

      public Object callData(DAOContext m_context) {

            logger = Logger.getLogger(this.getClass());

            context = m_context;

            PreparedStatement ps=null;

            try{

//获得连接

                  connection = getConnection(context);

                  String sql = getQuery(context, Queries.SQL_USER_INSERT);

                  try{

                        ps = connection.prepareStatement(sql);

                        //执行sql

                  }finally{

                        ps.close();

                  }

            }

            catch (SQLException ex){

                  ex.printStackTrace();

                  logger.equals(ex);

            }catch(DAOException e){

                  e.printStackTrace();

                  logger.error(e);

            }

            return null;

      }    

     

 

}

 

public class JDBCDAOObject extends DAOObject {

      /**

       * Gets the current connection.

       */

      protected Connection getConnection (DAOContext context) throws DAOFactoryException

      {

//首先获得jdbc Factory,然后获得daosource,最后获得daosourceconnection

            JDBCDAOSource source = (JDBCDAOSource)getDAOFactory().getDAOSource(context);

            return source.getConnection();

      }

}

这篇关于实现可扩展的DAO,本文给出实现DAO的编程思想。的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/950868

相关文章

shell编程之函数与数组的使用详解

《shell编程之函数与数组的使用详解》:本文主要介绍shell编程之函数与数组的使用,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录shell函数函数的用法俩个数求和系统资源监控并报警函数函数变量的作用范围函数的参数递归函数shell数组获取数组的长度读取某下的

openCV中KNN算法的实现

《openCV中KNN算法的实现》KNN算法是一种简单且常用的分类算法,本文主要介绍了openCV中KNN算法的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的... 目录KNN算法流程使用OpenCV实现KNNOpenCV 是一个开源的跨平台计算机视觉库,它提供了各

OpenCV图像形态学的实现

《OpenCV图像形态学的实现》本文主要介绍了OpenCV图像形态学的实现,包括腐蚀、膨胀、开运算、闭运算、梯度运算、顶帽运算和黑帽运算,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起... 目录一、图像形态学简介二、腐蚀(Erosion)1. 原理2. OpenCV 实现三、膨胀China编程(

通过Spring层面进行事务回滚的实现

《通过Spring层面进行事务回滚的实现》本文主要介绍了通过Spring层面进行事务回滚的实现,包括声明式事务和编程式事务,具有一定的参考价值,感兴趣的可以了解一下... 目录声明式事务回滚:1. 基础注解配置2. 指定回滚异常类型3. ​不回滚特殊场景编程式事务回滚:1. ​使用 TransactionT

Android实现打开本地pdf文件的两种方式

《Android实现打开本地pdf文件的两种方式》在现代应用中,PDF格式因其跨平台、稳定性好、展示内容一致等特点,在Android平台上,如何高效地打开本地PDF文件,不仅关系到用户体验,也直接影响... 目录一、项目概述二、相关知识2.1 PDF文件基本概述2.2 android 文件访问与存储权限2.

使用Python实现全能手机虚拟键盘的示例代码

《使用Python实现全能手机虚拟键盘的示例代码》在数字化办公时代,你是否遇到过这样的场景:会议室投影电脑突然键盘失灵、躺在沙发上想远程控制书房电脑、或者需要给长辈远程协助操作?今天我要分享的Pyth... 目录一、项目概述:不止于键盘的远程控制方案1.1 创新价值1.2 技术栈全景二、需求实现步骤一、需求

Spring Shell 命令行实现交互式Shell应用开发

《SpringShell命令行实现交互式Shell应用开发》本文主要介绍了SpringShell命令行实现交互式Shell应用开发,能够帮助开发者快速构建功能丰富的命令行应用程序,具有一定的参考价... 目录引言一、Spring Shell概述二、创建命令类三、命令参数处理四、命令分组与帮助系统五、自定义S

SpringBatch数据写入实现

《SpringBatch数据写入实现》SpringBatch通过ItemWriter接口及其丰富的实现,提供了强大的数据写入能力,本文主要介绍了SpringBatch数据写入实现,具有一定的参考价值,... 目录python引言一、ItemWriter核心概念二、数据库写入实现三、文件写入实现四、多目标写入

Android Studio 配置国内镜像源的实现步骤

《AndroidStudio配置国内镜像源的实现步骤》本文主要介绍了AndroidStudio配置国内镜像源的实现步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,... 目录一、修改 hosts,解决 SDK 下载失败的问题二、修改 gradle 地址,解决 gradle

SpringSecurity JWT基于令牌的无状态认证实现

《SpringSecurityJWT基于令牌的无状态认证实现》SpringSecurity中实现基于JWT的无状态认证是一种常见的做法,本文就来介绍一下SpringSecurityJWT基于令牌的无... 目录引言一、JWT基本原理与结构二、Spring Security JWT依赖配置三、JWT令牌生成与