Pete Barrett said:
What exactly do you mean by 'generic' code? All the database code will
be generic once the Connection is obtained, so what I usually do is to
centralise all the database access in a single class, and provide the
Connection in an open() method. Is that the sort of 'generic' code you
had in mind? (Obviously, there are other equally generic ways of doing
it apart from the way I prefer.)
yes thats what i have in my mind. I have identified that
1) to get a javax.sql.DataSource connection, I need:
1.1) a JNDI name
2) to ge a java.sql.DriverManager connection, I need:
2.1) Driver Name
2.2) Database URL
2.3) Database User Id
2.4) Database Password
Now I can create one class which has 2 methods:
public class ConnectionUtil {
// used by the app using JBoss
public Connection getDataSourceConnection( String jndiName ) {...}
// used by the app not using JBoss
public Connection getDriverManagerConnection( String driverName, String
databaseUrl, String databaseUserId, String databasePassword) {...}
}
Another option i can think of which is cleaner is to have a Connection
interface:
public interface ConnectionI {
public Connection getConnection(Properties props);
}
Then 2 seperate classes one for DataSource and one for DriverManager which
implements the interface
public class DataSourceConnection implements ConnectionI {
private String jndiName;
// props contains JNDI Name
public Connection getConnection(Properties props) {...}
}
public class DriverManagerConnection implements ConnectionI {
private String driverName;
private String databaseUrl;
private String databaseUserId;
private String databasePassword;
// props contains Driver Name, Database Url, Database User Id, Database
Password
public Connection getConnection(Properties props) {...}
}
Then a factory:
public class ConnectionFactory {
public static final int DATASOURCE = 1;
public static final int DRIVERMANAGER = 2;
public ConnectionI getConnectionI( int connType, Properties props ) {
switch(connType)
case DRIVERMANAGER:
return new DriverManagerConnection( props );
case DATASOURCE:
return new DataSourceConnection( props);
default:
return null;
}
}
So the test code to get a DataSource Connection would be:
Properties props = new Properties();
prop.put("JNDINAME", "MSSQLDS");
ConnectionI connectionI = ConnectionFactory.getConnectionI(1, props);
java.sql.Connection conn = connectionI.getConnection();
And the test code to get a DriverManager Connection would be:
Properties props = new Properties();
prop.put("DRIVERNAME", "sun.jdbc.odbc.JdbcOdbcDriver");
prop.put("DATABASEURL", "jdbc
dbc:database_odbc");
prop.put("DATABASEUSERID", "sa");
prop.put("DATABASEPASSWORD", "password");
ConnectionI connectionI = ConnectionFactory.getConnectionI(2, props);
java.sql.Connection conn = connectionI.getConnection();
What do you think which solution is more gneric and more maintainable?