How to use JNDI to get database connection or data source

In this tutorial you will learn, how to use JNDI to get database connection or data source.

Tools and Technologies used:

  • Java 5 or above
  • Eclipse Indigo
  • Spring MVC 3.0
  • MySQL 5.5
  • JBOSS Server 4.2.2

First create a new Dynamic Web Project and configure it as Maven Project. For Reference, Click Here

Add the following dependencies in pom.xml

   <!-- Spring 3 dependencies -->

1. Sql Script

Sql Script for creating table and insert records are as follows.

Create table employee(employee_id int(10) not null primary key,employee_name varchar(50));
insert into employee values(1,'Puneet Aggarwal');
insert into employee values(2,'Sahil Verma');

2. Data Source Configuration

Create a mysql-ds.xml file under the directory jboss-4.2.2.GA\server\default\deploy

<?xml version="1.0" encoding="UTF-8"?>

3. JNDI to get Connection

In your class file, write the following code to get the connection.

private Connection getJNDIConnection(){
    String DATASOURCE_CONTEXT = "java:employee";
    Connection result = null;
    try {
      Context initialContext = new InitialContext();
      DataSource datasource = (DataSource)initialContext.lookup(DATASOURCE_CONTEXT);
      if (datasource != null) {
        result = datasource.getConnection();
      else {
          System.out.println("Failed to lookup datasource.");
    catch ( NamingException ex ) {
        System.out.println("Cannot get connection: " + ex);
    catch(SQLException ex){
        System.out.println("Cannot get connection: " + ex);
    return result;
Connection connection = getJNDIConnection();
if (connection != null) {  

The folder structure of the example is shown below in Figure 3.1

Figure 3.1 Figure 3.1

You can download the source code of this example here.

No comments yet.

Leave a Reply