Search code examples
connection-poolingtomcat8ojdbc

Options to connect to Oracle8 through tomcat 8.5


I am working on a war running on Tomcat 8.5.40, compiled with jdk 8.261 and I need to connect to Oracle with an ojdb8-19.3.0.0 driver. There will be more wars connecting to the same database.

AFAIK and found in the documentation, there are two main ways to implement the connections:

As I am concerned about performance of the connections, I will use Connection Pool. My question is:

Are both approaches the same in terms of performance?

I just wonder if using Contexts, tomcat manages better the pool, specially when there are multiple wars using it.


Solution

  • There are a couple of disadvantages in configuring datasources in code instead of JNDI:

    • You introduce a dependency of your code on tomcat-jdbc and a specific version of this library. This means, that your application will work only on specific versions of Tomcat.

    • You lose the advantages of connection pooling between applications: if you create the datasources programmatically, every application will have its own connection pool. On the other hand, by using JNDI you can decide whether to create one datasource per application or share a global one (see Context versus GlobalNamingResources).

      If you use a global datasource the idle connections of your pool are available to all applications, therefore the need to open new TCP/IP connections to the database occurs less often (the cost in time of establishing a new TCP/IP connection is of the order of milliseconds, so relatively high).

    GlobalNamingResources example

    Configure a data source in server.xml:

    <GlobalNamingResources>
        <Resource auth="Container"
                  type="javax.sql.DataSource"
                  name="jdbc/globalDb"
                  username="username"
                  password="secret"
                  url="jdbc:..." />
        ...
    </GlobalNamingResources>
    

    Add a <ResourceLink> to your context file:

    <Context>
        <ResourceLink name="jdbc/db"
                      global="jdbc/globalDb"
                      type="javax.sql.DataSource" />
        ...
    </Context>