Marco M. Marco M. - 3 months ago 17
Java Question

NullPointerException of datasource in initiating the connection pool

So I have a code in the context.xml which contains the information for the connection of my database

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




<Resources name="jdbc/murach" auth="Containter"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/murach"
username="root" password="root"
maxActive="100" maxIdle="30" maxWait="10000"
logAbandoned="true" removeAbandoned="true"
removeAbandonedTimeout="60" type="javax.sql.DataSource" />

<ResourceLink name="jdbc/murach"
global="jdbc/mydb"
type="javax.sql.DataSource" />




While for the Connection Pool I created a class to initiate and to connect it to the database. the error begins in the method of
getConnection()
and I know that the problem might be residing in the
dataSource = (DataSource) ic.lookup("java:/comp/env/jdbc/murach");
May I ask what should i really put in the lookup for it to work. By the way the error is
NullPointerException
in the return of the
datasource.getConnection()


package lars.data;

import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;


public class ConnectionPool {
private static ConnectionPool pool = null;
private static DataSource dataSource = null;

private ConnectionPool() {
try {
InitialContext ic = new InitialContext();
dataSource = (DataSource) ic.lookup("java:/comp/env/jdbc/murach");
System.out.print(dataSource);
} catch (NamingException e) {
System.out.println(e);
}
}

public static synchronized ConnectionPool getInstance() {
if (pool == null) {
pool = new ConnectionPool();
}
return pool;
}

public Connection getConnection() {
try {
return dataSource.getConnection();
} catch (SQLException e) {
System.out.println(e);
return null;
}
}

public void freeConnection(Connection c) {
try {
c.close();
} catch (SQLException e) {
System.out.println(e);
}
}
}

Answer

I believe that your problem is in the configuration of your ResourceLink especially the value of the attribute global that should match with the value defined in your Resource, it should be:

 <ResourceLink name="jdbc/murach"
         global="jdbc/murach"
          type="javax.sql.DataSource" />

global: The name of the linked global resource in the global JNDI context.

name: The name of the resource link to be created, relative to the java:comp/env context.

NB 1: The name of the node that defines a resource is Resource not Resources. In other words it should be:

<Resource name="jdbc/murach" ... />

NB 2: You should try ic.lookup("java:comp/env/jdbc/murach")