StripeswithGuiceでデータベース接続を管理するために使用するベストプラクティスについて疑問に思っています。理想的には、次のことを強制したいと思います。
スレッド/httpリクエストごとに1つのdb接続が使用されます(おそらく、ServletScope.REQUESTスコープを使用してプロバイダーへの接続をguiceでバインドします)。すべてのクエリは1つのトランザクションで実行され、最後にコミットまたはロールバックされます。
私の質問は、データベース接続を作成/閉じるにはどうすればよいですか?
Stripes Interceptorを使用して接続を開閉するのは悪い考えですか?
データベース内のさまざまなテーブルに対してカスタムSQLクエリを実行するManagerクラスの大規模な接続があります。現在、これらすべてのManagerクラスには、次のようなメソッドがあります。
public abstract class MyManagerBase implements IMyManager {
@Inject
public void setConnection(Connection conn) {
this.conn = conn;
}
}
管理者自身がこれをサブクラス化し、接続を作成または閉じません。
私はこのようなアクションBeanを持っています:
public class MyActionBean implements ActionBean {
@Inject IMyManager myManager;
@DefaultHandler
public Resolution save() {
myManager.doStuff(...);
}
...
}
私はこのようなguice設定を持っています:
public class MyConfigModule extends AbstractModule {
@Override
protected void configure() {
install(new ServletModule());
bind(IMyManager.class).to(MyManagerImpl.class);
bind(Connection.class).toProvider(MyConnectionProvider.class).in(ServletScopes.REQUEST);
}
これまでのところ、インターセプターを使用してマネージャーを注入すると同時に、そのhttpリクエストのすべてのマネージャーに同じ接続を使用することを考えています。
私のインターセプターの試みは、これまでのところ次のようになっています。
@Override
public Resolution intercept(ExecutionContext executionContext) throws Exception {
Connection conn = null;
switch( executionContext.getLifecycleStage() ) {
case ActionBeanResolution:
log.debug("Intercepting: ActionBeanResolution");
// Inject dependencies into ActionBeans
injector.injectMembers( executionContext.getActionBeanContext() );
Resolution resolution = executionContext.proceed();
injector.injectMembers( executionContext.getActionBean() );
return resolution;
case RequestComplete:
log.debug("Intercepting: RequestComplete");
executionContext.getActionBean();
Connection conn = injector.getInstance(Connection.class);
conn.commit();
conn.close();
}
}
}