Java Database Connectivity4.34.24.14.0
This feature enables the configuration of DataSources to access Databases from applications. Any JDBC driver that complies with the JDBC 4.2, 4.1, 4.0, 3.0, or 2.x specification can be used; customized configuration of many specific providers is included. High performance connection pooling is also provided.
Enabling this feature
To enable the Java Database Connectivity 4.2 feature, add the following element declaration into your server.xml
file, inside the featureManager
element:
<feature>jdbc-4.2</feature>
Examples
Simple DataSource example
To configure a data source, two configuration elements are typically required:
-
Shared library containing JDBC driver file(s)
-
One or more data source elements using the the shared library
The following example creates a data source that can be injected using the name jdbc/myDataSource
. If the jndi-1.0 feature is enabled, that name can be used as a JNDI name:
<library id="JdbcLib">
<fileset dir="server1/jdbc"/>
</library>
<dataSource jndiName="jdbc/myDataSource">
<jdbcDriver libraryRef="JdbcLib"/>
<properties databaseName="myDB" serverName="mydb.mycompany.com" portNumber="50000"/>
</dataSource>
A Servlet or EJB can then get it injected for use:
@Resource(name="jdbc/myDataSource")
private DataSource myDb;
public void insertRochester() throws SQLException {
try (Connection con = myDataSource.getConnection()) {
con.createStatement().executeUpdate("INSERT INTO CITIES VALUES('Rochester', 'MN', 'US')");
}
}
DataSource with authentication
When connecting to remote databases, credentials typically need to be provided.
These can be configured using an authData
element. The password can be in
plain text, xor, or aes encrypted. The securityUtility encode
command can be
used to create an encoded password. The following example encodes password
as the
password value:
<authData id="dbCreds" user="dbUser" password="{aes}AEJrzAGfDEmtxI18U/qEcv54kXmUIgUUV7b5pybw/BzH" />
<dataSource jndiName="jdbc/myDataSource" containerAuthDataRef="dbCreds">
<jdbcDriver libraryRef="JdbcLib"/>
<properties databaseName="myDB" serverName="mydb.mycompany.com" portNumber="50000"/>
</dataSource>
Using JDBC driver classes from an application
Some applications make use of JDBC driver classes using Connection.unwrap
. This
means the application needs to be able to view the JDBC driver classes. This is
done by configuring the application classloader to see the JDBC driver classes:
<library id="JdbcLib">
<fileset dir="server1/jdbc"/>
</library>
<webApplication location="myweb.war" >
<classloader commonLibraryRef="JdbcLib" />
</webApplication>
<dataSource jndiName="jdbc/myDataSource">
<jdbcDriver libraryRef="JdbcLib"/>
<properties databaseName="myDB" serverName="mydb.mycompany.com" portNumber="50000"/>
</dataSource>