I have some c3p0 pool encapsulated in a class that I use to execute SQL statements.
It’s initialized this way:
public PooledQueryExecutor(String url, Properties connectionProperties) throws DALException {
try {
dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(DRIVER);
dataSource.setJdbcUrl(url);
dataSource.setProperties(connectionProperties);
} catch (PropertyVetoException ve) {
throw new DALException(ve);
}
}
Then – inside the same class – I use some methods to perform basic tasks:
public CachedRowSet executeSelect(String sql) throws DALException {
// Get a connection, execute the SQL, return the rows that match, return resources to the pool
}
The “question” is:
I have a lot of different classes that represent network packets that I receive. Most classes need to have this PooledQueryExecutor to perform DB operations, but some don’t. Do I pass this PooledQueryExecutor to the constructor of the classes that need it (80% of the packets), or do I make the PooledQueryExecutor a singleton? Or maybe “something else”? I also though of using a ThreadLocal to avoid polluting my constructor, but I don’t think that’s a good idea, is it?
EDIT: It’s not a web application, and no dependency injection framework is currently used.
Thank you for your time!
I assume you are not using any DI framework? If this is the case you have a few choices:
Pass
PooledQueryExecutorto the constructor of classes that require it. This is actually pretty good from testing and architecture perspective.let the classes requiring JDBC implement some simple interface like:
Then you can even iterate over classes and discover which implement this and inject
PooledQueryExecutorwhere needed. You are one step to rediscovering DI here, but never mind.Similar approach would be to create an abstract base class that would require
PooledQueryExecutorAwareas a dependency and haveprotected finalfield holding it.Let every class be aware
PooledQueryExecutor– not recommended, unnecessary couplingSingleton is the worst what you can do, untestable and hard to understand code. Please, don’t.
ThreadLocal? Forget about it. Remember, explicitness is king.Also have a look at JdbcTemplate. It is part of the Spring, but you can only include
spring-jdbc.jarand few other without using the whole framework. I think it can easily replace yourPooledQueryExecutor.