On a DataSource interface I found two methods to get Connection, with and without username and password paramenters.
Connection getConnection() Connection getConnection(String username, String password)
Stated that I’d like to use a connection pool exposed as JNDI Resource from the server (tomcat) what differences are from the two methods?
Depending on the
DataSourceimplementation, these two methods do different things. The first, with no arguments, simply obtains aConnectionfrom the pool, configured with credentials configured when theDataSourcewas created. The second, which accepts new credentials, will obtain a Connection from theDataSourcethat was opened using those credentials, or it will create a newConnectionwith those credentials or — if the JDBC driver supports it — it will take an existingConnectionand switch the credentials (I’m not sure if this is really even possible).Unfortunately, the JavaDoc (http://docs.oracle.com/javase/7/docs/api/javax/sql/DataSource.html) does not really give you any insight to why one might call one versus the other. The obvious reason is because you want to connect using credentials other than those configured for the entire
DataSource.The default
DataSourcethat Tomcat will configure for you is aBasicDataSourcefrom the Apachecommons-dbcp: this DataSource does not support thegetConnection(String username, String password)method. Recent versions of Tomcat ship withtomcat-pool, which is an alternative DataSource implementation that does support this alternative mechanism (although the current documentation says it does not) if you set thealternateUsernameAllowed="true"attribute on your<Resource>element.Tomcat-pool documentation: http://tomcat.apache.org/tomcat-7.0-doc/jdbc-pool.html