Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a JNDI Resource in a JAX-RS (Jersey) Application?

I'm trying to set up a connection to my database through a Tomcat JNDI resource. I've been looking at many articles today and I can't seem to find an answer.

In my server.xml I have:

  <GlobalNamingResources>
  <Resource name="jdbc/MyDB" auth="Container" type="javax.sql.DataSource"
      maxActive="100" maxIdle="30" maxWait="10000"
      username="tomcat" password="...."
      driverClassName="com.mysql.jdbc.Driver"
      url="jdbc:mysql://localhost:3333/tomcat?autoReconnect=true"/>

  .....
  </GlobalNamingResources>

In my web service, I attempt to access the resource with:

    InitialContext ctx = new InitialContext();
    DataSource data = (DataSource)ctx.lookup("java:comp/env/jdbc/MyDB");
    Connection conn = data.getConnection();

When I run the code, I get this exception:

Nov 2, 2011 1:06:20 PM com.sun.jersey.spi.container.ContainerResponse  mapMappableContainerException
SEVERE: The exception contained within MappableContainerException could not be mapped to a response, re-throwing to the HTTP container
javax.naming.NameNotFoundException: Name jdbc is not bound in this Context
...

I have the newest mysql-connector-java-5.1.18-bin.jar in both my web-app's lib and my tomcat lib.

Can you please help me get this working?

like image 886
Blaskovicz Avatar asked Nov 13 '22 15:11

Blaskovicz


1 Answers

I use this code, with only the name of the resource, and it works:

private Connection getConnection(){
      final Context ctx = new InitialContext();
      final DataSource ds = (DataSource) ctx.lookup("jdbc/MyDB");
      if (ds != null)
      {
             return ds.getConnection();
      }
      else
      {

      }
}
like image 158
cgalleguillosm Avatar answered Dec 10 '22 07:12

cgalleguillosm