正确使用JDBC连接池(Glassfish)
我需要在作为会话bean实现的Java Web服务中建立数据库连接,我不确定我是否正确执行。
我创建了一个类
public final class SQLUtils { //..... private static DataSource m_ds=null; static { try { InitialContext ic = new InitialContext(); m_ds = (DataSource) ic.lookup(dbName); //Connection pool and jdbc resource previously created in Glassfish , dbName contains the proper JNDI resource name } catch (Exception e) { e.printStackTrace(); m_ds = null; } } public static Connection getSQLConnection() throws SQLException { return m_ds.getConnection(); } }
每当我需要连接时,我都会这样做
Connection cn = null; try { cn = SQLUtils.getSQLConnection(); // use connection } finally { if (null != cn) { try { cn.close(); } catch (SQLException e) { } } }
以这种方式使用它是否可以,或者我DataSource必须是bean的成员?
@Stateless @WebService public class TestBean { private @Resource(name=dbName) DataSource m_ds; }
如果这是一个nube问题,我很抱歉,但我对Java很新。 提前致谢。
除了C风格的格式化,一些不必要的行和有点差的exception处理,你可以这样做。
我是这样做的:
public final class SQLUtil { private static DataSource dataSource; // .. static { try { dataSource = (DataSource) new InitialContext().lookup(name); } catch (NamingException e) { throw new ExceptionInInitializerError(e); } } public static Connection getConnection() throws SQLException { return dataSource.getConnection(); } }
我抛出ExceptionInInitializerError
以便应用程序将立即停止,以便您在尝试获取连接时不需要面对“无法解释的” NullPointerException
。
在古老的J2EE世界中,管理它的传统方法是使用ServiceLocator
。 下面是一个示例实现(非优化,可以缓存DataSource
):
public class ServiceLocator { private Context initalContext; private static ServiceLocator ourInstance = new ServiceLocator(); public static ServiceLocator getInstance() { return ourInstance; } private ServiceLocator() { try { this.initalContext = new InitialContext(); } catch (NamingException ex) { throw new ServiceLocatorException(...); } } public DataSource getDataSource(String dataSourceName) { DataSource datasource = null; try { Context ctx = (Context) initalContext.lookup("java:comp/env"); datasource = (DataSource) ctx.lookup(dataSourceName); } catch (NamingException ex) { throw new ServiceLocatorException(...); } return datasource; } }
要使用它,只需调用它:
DataSource ds = ServiceLocator.getInstance().getDataSource("jdbc/mydatabase");
但这是在EJB3和dependency injection时代之前。 现在,在使用EJB3时,如果已在EJB容器中设置了DataSource
, 那么在无状态Bean中自动注入DataSource
要做的就是编写 (其中mydatabase
是数据源的名称):
@Resource private DataSource mydatabase;
如果要显式地使用name属性,请设置名称:
@Resource(name="jdbc/mydatabase") private DataSource dataSource;
EJB3实际上使ServiceLocator
模式过时,在使用它时你应该更喜欢注入。
嗯,这不是JDBC数据源的示例,而不是Glassfish连接池吗?