I must say that, based on the materials on the site, I am not impressed by DBConnectionBroker. Today's
JDBC API has a standard way of acquiring connections which can be pooled or even part of a distributed transaction: the
DataSource. It is standardised, making your application much more portable, and also easier to use: you give a connection back to the pool simply by close()ing it like you do with a normal connection.
So does this answer your question? It does, actually, because your question now becomes: where do I get my DataSource from? There are a number of alternatives.
The J2EE way is to ask your application server to set up a DataSource for you. Every app server should be able to do this. This has two advantages: (a) it's the least amount of work and (b) assigning a database to the application becomes a deployment task. You can use JNDI to look up this DataSource anywhere in your application.You can use a connection pool that exposes a DataSource interface, such as Apache Jakarta DBCP. This gives you complete control over how you instantiate it, where you bind it, and so forth.Some JDBC drivers come with a connection pool implementation. Of course this makes you driver-dependent, but often that's OK.Finally, you may sometimes still find that you need a Connection or DataSource in a layer of your application that doesn't have easy access to it. You can pass a Connection as a simple method argument
Alternatively, if you need to make a number of method calls as part of a transaction and want to avoid the Connection cluttering up all your methods, you can use an instance variable
An instance of this FooBarDAO would typically be created as part of an ongoing transaction, and forgotten about once the transaction is complete.
You would treat a DataSource a bit differently. A DataSource is just a factory for Connection objects and your code needs just a single DataSource that it uses whenever it needs to access the database. You'd use a DataSource if you want the work to be done in an independent transaction (please note that this is
not true at all in a managed environment such as an EJB container). You could conceivably use a static variable somewhere to store the DataSource used by your application, but I must admit I don't really like that much; just look the thing up in JNDI at initialisation time if you can.
Does that help?
- Peter