You are pretty much right about having to configure JNDI resources separately. The only thing that in web.xml there is NO <env-ref>
element, but <resource-env-ref>
and <resource-ref>
elements.
In order to use more databases, you have to make the following additional configurations for each resource:
- add a new
<Resource>
in context.xml file
- add a new
<resource-ref>
or <resource-env-ref>
in web.xml file
NOTE:
If you use @Resource
annotation, the new resource no longer needs to be defined in the deployment descriptor (web.xml). This annotation is equivalent to declaring a resource-ref, message-destination-ref or env-ref, or resource-env-ref element in the deployment descriptor.
And accordingly you have to separately lookup each DataSource from the InitialContext (you can look up the required DataSource once and then just use the same instance).
Example
The below is an example of configuring two MySQL databases from one of my projects. One database is configured utilizing The Tomcat JDBC Connection Pool, another without connection pooling (you can do it however you like/need).
context.xml (located in /META-INF directory):
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<!-- Configuration for primary DB -->
<Resource name="jdbc/TestShopDB"
type="javax.sql.DataSource"
auth="Container"
factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/test_shop"
username="root"
password="mysql"
maxActive="100"
minIdle="10"
initialSize="10"
validatonQuery="SELECT 1"
validationInterval="30000"
removeAbandoned="true"
removeAbandonedTimeout="60"
abandonWhenPercentageFull="50"
closeMethod="close"/>
<!-- Configuration for administration DB -->
<Resource name="jdbc/TestShopAdminDB"
type="javax.sql.DataSource"
auth="Container"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/test_shop_admin"
username="root"
password="mysql"/>
</Context>
web.xml (located in /WEB-INF directory; unrelated parts are omitted for the sake of brevity):
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
...
<!-- Configuration for primary DB -->
<resource-ref>
<res-ref-name>jdbc/TestShopDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
<!-- Configuration for administration DB -->
<resource-ref>
<res-ref-name>jdbc/TestShopAdminDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
...
</web-app>
Additional reading