简体   繁体   English

在Tomcat 7 jdni中将资源查找集中在一个类中

[英]Centralize in a single class the lookup of a resource in Tomcat 7 jdni

I'm creating a web app using NetBeans and Tomcat 7 and I wanted to create my first connection pool. 我正在使用NetBeans和Tomcat 7创建一个Web应用程序,我想创建我的第一个连接池。 I've followed all the steps in the tomcat documentation here: http://tomcat.apache.org/tomcat-7.0-doc/jndi-datasource-examples-howto.html 我已经按照以下位置的tomcat文档中的所有步骤进行操作: http : //tomcat.apache.org/tomcat-7.0-doc/jndi-datasource-examples-howto.html

But in my application I'll have many DAO objects with many different methods each, so I'd like to avoid writing the code for looking up the datasource and getting a connection in each and every method that access to the DB, so I've created a class to centralize this operation and return a connection to the different DAO objects. 但是在我的应用程序中,我将有很多DAO对象,每个对象都有许多不同的方法,因此我要避免编写代码来查找数据源并在访问数据库的每个方法中获得连接,所以我ve创建了一个类来集中此操作,并返回到不同DAO对象的连接。

You can see the code below, but as I said it's my first time wth this, so I'm not sure... does this make sense for you? 您可以看到下面的代码,但是正如我所说的,这是我第一次这样做,所以我不确定...这对您有意义吗? is there a better way to do something like that? 有没有更好的办法来做这样的事情? or it's just better to write this code in each method? 还是最好在每种方法中编写此代码?

And if this does make sense, could I use the Context or even also the DataSource as static attributes to avoid continuous lookups? 如果这确实有意义,我是否可以使用Context甚至DataSource作为静态属性来避免连续查找?

Thanks very much! 非常感谢!

My ConnectionPool class: 我的ConnectionPool类:

package dao.mysql;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.apache.tomcat.jdbc.pool.DataSource;


public class ConnectionPool {

    public static Connection getConnection() {
        Connection connection = null;
        try {            
            Context initCtx = new InitialContext();
            Context envCtx = (Context) initCtx.lookup("java:comp/env");
            DataSource ds = (DataSource)envCtx.lookup("jdbc/EmployeeDB");

            connection = ds.getConnection();

        } catch (SQLException ex) {
            Logger.getLogger(ConnectionPool.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NamingException ex) {
            Logger.getLogger(ConnectionPool.class.getName()).log(Level.SEVERE, null, ex);
        }
        return connection;
    }
}

您可以按照本文此处所述,将JDBC连接池用作单例bean

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM