How to Create a Single Non Closable JDBC Connection
When using embedded databases (e.g. Apache Derby in embedded mode) this is a good idea to have just one connection to the db, because multiple connections to a single db in embedded mode usually cause deadlocks or runtime exceptions. To create a single connection we can use a static method which returns a single connection every time called, but the problem is that when the close method is called on the connection everything is destroyed! To solve this problem I have used a mixture of Singleton and Proxy design patterns, here is the code:
import java.sql.*; import java.util.*; public class SingleConnection implements Connection { private Connection connection; private static SingleConnection instance = new SingleConnection(); public static SingleConnection getInstance() { return instance; } private SingleConnection() { try { Class.forName("org.apache.derby.jdbc.EmbeddedDriver"); String connectionString = "jdbc:derby:testdb;create=true"; connection = DriverManager.getConnection(connectionString); } catch (Exception e) { throw new RuntimeException(e); } } public void close() throws SQLException { // throw new RuntimeException("Not Allowed to Close Connection"); } public void clearWarnings() throws SQLException { connection.clearWarnings(); } // delegate to rest of methods ... } |
SingleConnection implements the Connection interface and wraps an instance of connection, every call to SingleConnection is delegated to actual connection instance (proxy), except close which runs a custom code(does nothing!). The constructor is made private and an accessor method is added to return the single instance of SingleConnection (Singleton pattern).
2 comments:
You mean "How to create ..." ?
Connection conn = SingleConnection.getInstance();
// use conn
Post a Comment