【发布时间】:2012-12-10 14:53:58
【问题描述】:
我正在使用 NetBeans 和 Tomcat 7 创建一个 Web 应用程序,并且我想创建我的第一个连接池。 我已按照此处的 tomcat 文档中的所有步骤进行操作: http://tomcat.apache.org/tomcat-7.0-doc/jndi-datasource-examples-howto.html
但是在我的应用程序中,我将有许多 DAO 对象,每个对象都有许多不同的方法,所以我想避免编写代码来查找数据源并在每个访问数据库的方法中获取连接,所以我创建了一个类来集中这个操作并返回到不同 DAO 对象的连接。
您可以看到下面的代码,但正如我所说,这是我第一次使用这个,所以我不确定......这对你有意义吗?有没有更好的方法来做这样的事情?还是在每个方法中都写这段代码更好?
如果这确实有意义,我可以使用 Context 甚至 DataSource 作为静态属性来避免连续查找吗?
非常感谢!
我的 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;
}
}
【问题讨论】:
标签: java tomcat7 jndi connection-pooling