次の JDBC/MySQL の Connector/J リファレンスでは、InitialContext と Datasource のインスタンスをキャッシュすることを提案しています。プライベートな静的インスタンスにするだけでキャッシングは解決しますか? スレッドセーフを気にする必要はありませんか (もしあれば)。これを Web アプリ (Restlet + glassfish/Java EE + mysql) にキャッシュするのに最適な「場所」は??
いわば、データ アクセス クラスのルートである GenericDAO クラスがあります。では、静的インスタンスを持つだけで実際に問題が解決するのでしょうか? 一部のメソッドを強制的に静的にする必要がありますが、これは望ましくありません。提案??
ありがとう!
public void doSomething() throws Exception {
/*
* Create a JNDI Initial context to be able to
* lookup the DataSource
**
In production-level code, this should be cached as
* an instance or static variable, as it can
* be quite expensive to create a JNDI context.
**
Note: This code only works when you are using servlets
* or EJBs in a Java EE application server. If you are
* using connection pooling in standalone Java code, you
* will have to create/configure datasources using whatever
* mechanisms your particular connection pooling library
* provides.
*/
InitialContext ctx = new InitialContext();
/*
* Lookup the DataSource, which will be backed by a pool
* that the application server provides. DataSource instances
* are also a good candidate for caching as an instance
* variable, as JNDI lookups can be expensive as well.
*/
DataSource ds =
(DataSource)ctx.lookup("java:comp/env/jdbc/MySQLDB");
/*
*Remaining code here...
*/
}