How to get same connection from a DataSource in multiple classes? Is it possible?
Suppose I have a DataSource which I pass to 2 classes. The DataSource is using a Connection Pooling.
Then I call a method in 1st Class which get a Connection from the DataSource, uses that Connection and then closes that Connection.
Then I call a method in 2nd Class which get a Connection from the DataSource, uses that Connection and then closes that Connection.
Is it possible to be sure that the method in 2nd Class will get the same Connection which was used by method in 1st Class?
This is the example code:
This is the 1st class whose method will be called by the unit of work:
public class Class1 {
private DataSource dataSource = null;
public Class1(DataSource dataSource) {
this.dataSource = dataSource;
}
public void class1Method1() throws Exception {
Connection conn = null;
try {
conn = dataSource.getConnection();
... // do your work
} finally {
try {
if (conn != null)
conn.close();
} catch (Exception e) {
} finally {
conn = null;
}
}
}
}
This is the 2nd class whose method will be called by the unit of work:
public class Class2 {
private DataSource dataSource = null;
public Class2(DataSource dataSource) {
this.dataSource = dataSource;
}
public void class2Method1() throws Exception {
Connection conn = null;
try {
conn = dataSource.getConnection();
... // do your work
} finally {
try {
if (conn != null)
conn.close();
} catch (Exception e) {
} finally {
conn = null;
}
}
}
}
And this is my unit of work:
InitialContext initialContext = null;
DataSource dataSource = null;
Class1 class1 = null;
Class2 class2 = null;
initialContext = new InitialContext();
dataSource = (DataSource) initialContext.lookup("java:comp/env/jdbc/MyDB");
class1 = new Class1(dataSource);
class2 = new Class2(dataSource);
class1.class1Method1();
class2.class2Method1();