0

I'm trying to implement connection pooling for a JSF 2.1 application which has a H2 database and Jetty 9 Web server embedded in it. I have two options to implement connection pooling for the h2 database. The options being let Jetty implement connection pooling for me, or I define a application scoped managed bean which creates connection pool. I would like to know which would be a better approach in handling connection pooling?

Connection pooling using Application scoped managed bean:

JdbcConnectionPool cp = JdbcConnectionPool.create(
             "jdbc:h2:~/test", "sa", "sa");
         for (String sql : args) {
             Connection conn = cp.getConnection();
             conn.createStatement().execute(sql);
             conn.close();
         }
         cp.dispose();
4

1 回答 1

1

任何一种连接池方法都可以。连接池的实现有很多(各有优缺点),随心所欲。

如果您有要执行的语句列表,那么我不会为每个语句打开一个新连接。相反,使用相同的连接(和语句)执行所有语句:

JdbcConnectionPool cp = JdbcConnectionPool.create(
    "jdbc:h2:~/test", "sa", "sa");
...
Connection conn = cp.getConnection();
Statement stat = conn.createStatement();
for (String sql : args) {
    stat.execute(sql);
}
conn.close();
...
cp.dispose();

可以启动/停止连接池:

  • 在 Web 应用程序之外,作为资源(在我看来这有点复杂),例如在“使用 Tomcat 的数据库连接池”一文中描述的那样。您会找到类似的 Jetty 文档。

  • 使用ServletContextListener(也在 H2 文档中描述)。在我看来,这有点简单。缺点是连接池不能被多个 Web 应用程序使用。

于 2013-06-05T18:17:04.923 回答