实现可扩展的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

相关文章

Java深度学习库DJL实现Python的NumPy方式

《Java深度学习库DJL实现Python的NumPy方式》本文介绍了DJL库的背景和基本功能,包括NDArray的创建、数学运算、数据获取和设置等,同时,还展示了如何使用NDArray进行数据预处理... 目录1 NDArray 的背景介绍1.1 架构2 JavaDJL使用2.1 安装DJL2.2 基本操

最长公共子序列问题的深度分析与Java实现方式

《最长公共子序列问题的深度分析与Java实现方式》本文详细介绍了最长公共子序列(LCS)问题,包括其概念、暴力解法、动态规划解法,并提供了Java代码实现,暴力解法虽然简单,但在大数据处理中效率较低,... 目录最长公共子序列问题概述问题理解与示例分析暴力解法思路与示例代码动态规划解法DP 表的构建与意义动

java父子线程之间实现共享传递数据

《java父子线程之间实现共享传递数据》本文介绍了Java中父子线程间共享传递数据的几种方法,包括ThreadLocal变量、并发集合和内存队列或消息队列,并提醒注意并发安全问题... 目录通过 ThreadLocal 变量共享数据通过并发集合共享数据通过内存队列或消息队列共享数据注意并发安全问题总结在 J

SpringBoot+MyBatis-Flex配置ProxySQL的实现步骤

《SpringBoot+MyBatis-Flex配置ProxySQL的实现步骤》本文主要介绍了SpringBoot+MyBatis-Flex配置ProxySQL的实现步骤,文中通过示例代码介绍的非常详... 目录 目标 步骤 1:确保 ProxySQL 和 mysql 主从同步已正确配置ProxySQL 的

JS 实现复制到剪贴板的几种方式小结

《JS实现复制到剪贴板的几种方式小结》本文主要介绍了JS实现复制到剪贴板的几种方式小结,包括ClipboardAPI和document.execCommand这两种方法,具有一定的参考价值,感兴趣的... 目录一、Clipboard API相关属性方法二、document.execCommand优点:缺点:

nginx部署https网站的实现步骤(亲测)

《nginx部署https网站的实现步骤(亲测)》本文详细介绍了使用Nginx在保持与http服务兼容的情况下部署HTTPS,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值... 目录步骤 1:安装 Nginx步骤 2:获取 SSL 证书步骤 3:手动配置 Nginx步骤 4:测

Idea实现接口的方法上无法添加@Override注解的解决方案

《Idea实现接口的方法上无法添加@Override注解的解决方案》文章介绍了在IDEA中实现接口方法时无法添加@Override注解的问题及其解决方法,主要步骤包括更改项目结构中的Languagel... 目录Idea实现接China编程口的方法上无法添加@javascriptOverride注解错误原因解决方

轻松上手MYSQL之JSON函数实现高效数据查询与操作

《轻松上手MYSQL之JSON函数实现高效数据查询与操作》:本文主要介绍轻松上手MYSQL之JSON函数实现高效数据查询与操作的相关资料,MySQL提供了多个JSON函数,用于处理和查询JSON数... 目录一、jsON_EXTRACT 提取指定数据二、JSON_UNQUOTE 取消双引号三、JSON_KE

MySql死锁怎么排查的方法实现

《MySql死锁怎么排查的方法实现》本文主要介绍了MySql死锁怎么排查的方法实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录前言一、死锁排查方法1. 查看死锁日志方法 1:启用死锁日志输出方法 2:检查 mysql 错误

CSS3中使用flex和grid实现等高元素布局的示例代码

《CSS3中使用flex和grid实现等高元素布局的示例代码》:本文主要介绍了使用CSS3中的Flexbox和Grid布局实现等高元素布局的方法,通过简单的两列实现、每行放置3列以及全部代码的展示,展示了这两种布局方式的实现细节和效果,详细内容请阅读本文,希望能对你有所帮助... 过往的实现方法是使用浮动加