JNDI Datasource with MySQL

Harry · 12 Sep 2026 · 11 views

Why JNDI?

A JNDI DataSource is a connection pool managed by Tomcat. Your app looks it up by name instead of creating its own connections - pooling, failover and quotas are centralized.

Step 1 - Driver on the Classpath

# MySQL driver available to every app
cp mysql-connector-j-8.x.x.jar $CATALINA_HOME/lib/

Step 2 - Define the Resource

In META-INF/context.xml of your app (or conf/context.xml):

<Context>
  <Resource name="jdbc/MyDB" auth="Container"
            type="javax.sql.DataSource"
            driverClassName="com.mysql.cj.jdbc.Driver"
            url="jdbc:mysql://localhost:3306/mydb?useSSL=false&serverTimezone=UTC"
            username="app_user" password="secret"
            maxTotal="20" maxIdle="10" maxWaitMillis="10000"/>
</Context>

Step 3 - Reference It from web.xml

<resource-ref>
  <res-ref-name>jdbc/MyDB</res-ref-name>
  <res-type>javax.sql.DataSource</res-type>
  <res-auth>Container</res-auth>
</resource-ref>

Using It in Java

Context ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/MyDB");
try (Connection c = ds.getConnection();
     PreparedStatement ps = c.prepareStatement("SELECT 1")) {
    ResultSet rs = ps.executeQuery();
}

Spring Boot / Spring users: point spring.datasource.jndi-name=jdbc/MyDB and let Spring use the pool.

Key Points

  • JNDI pools connections centrally - no per-app driver management.
  • Pool size and timeouts are tuned in the Resource attributes.
  • Credentials live in Tomcat config, not in app code.
Share this post:

Comments (0)

Please login or register to comment.