-1

As I am creating different database connections on the basis of database credentials (i.e. JSON or POJO with all the credentials required to create a DB connection). e.g. Imagine a Map containing these (UUID and Connection)

{
 (UUID1, connection1)
 (UUID2, connection2)
 (UUID3, connection3)
 (UUID4, connection4)
}

For creating these connections, I am using the DBCP/C3PO. BasicDataSource Class. Since I need these different connections at runtime, that's why creating and maintaining them against a UUID.

Is there any better way to implement this?

2
  • There are several libraries that perform connection pooling for you. In most cases, as long as you use your database objects normally (closing, etc.) then the library will take care of the important details. In fact, JDBC pooling might be built in to some of the drivers for your database. Sep 15 '21 at 13:26
  • Thanks for the suggestion, I know about different connection pooling frameworks, But my requirement is to maintain different database connections and get those database connections on the basis of some unique Id (UUID). What I am trying to achieve is to use an In-Memory DB that will store the unique key and the connection object, then at runtime, I will use this key to get my connection object. Once I get my connection object I will perform some queries to get some resultSet. Sep 15 '21 at 13:54
0

Hash Map Lookup

You should be able to use a HashMap lookup. This is probably not thread-safe, so you would need to use a ReadWriteLock to enable multiple readers of the Dictionary, and only exclusively lock it when written to.

Example:

Map<String, String> map = new HashMap<String, String>();
map.put("0bf8cbc9-6230-42bc-9531-cc9bf24eb345", "
Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;
");
//...
System.out.println(map.get("0bf8cbc9-6230-42bc-9531-cc9bf24eb345"));

Don't use UUID

According to the RFC standard, UUIDs are "unique" but they are not cryptographically pseudorandom. Instead you should something like SecureRandom to generate your keys, and encode as base64 or hex.

(note: Some Java implementations are at least considered to be a secure implementation, but you probably shouldn't rely on that.)

Consider outputting a PoolObject from the dictionary

The output value of the dictionary could be a connection-string as you require today, but you might consider returning a PoolObject of some sort. Such a PoolObject would manage a pool of connections for the same ID, allowing fast connection reuse within a timeout period.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.