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

      }

}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值