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

本文介绍了在Tomcat、Struts和MySQL开发环境下实现可扩展DAO的方法。通过JNDI连接数据库,将JNDI和调用sql语句的类名保存在XML文件里,还详细说明了配置JNDI、web.xml,初始化DAO配置信息,以及实现JDBC的DAOFactory等步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

开发环境:本文使用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();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值