title: JNDI and javax.sql.DataSource
body: <p>I'm someone that used to do some J2EE coding in the past and I'm coming back into the fold to work on a new J2EE project. A lot has changed since 2001, so I need to ask this very basic question.</p>
  
  <p>I'm using syntax like this in my database class:  </p>
  
  <pre><code>@Resource(name = "jdbc/MyDatabase")  
  private javax.sql.DataSource dataSource;  
  </code></pre>
  
  <p>I understand this is a new feature (annotations) but I'm not really sure how it works. Later on in my class I make this call:  </p>
  
  <pre><code>Connection c = dataSource.getConnection();  
  </code></pre>
  
  <p>And it throws a NullPointerException everytime. I step into this in the debugger and as it turns out, dataSource IS null.  </p>
  
  <p>It seems magical and weird that I do not initialize dataSource myself in the code. Any idea what I'm doing wrong?  </p>
  
  <p>My web.xml contains the following block to establish the resource:</p>
  
  <pre><code>&lt;resource-env-ref&gt;
      &lt;resource-env-ref-name&gt;jdbc/MyDatabase&lt;/resource-env-ref-name&gt;
      &lt;resource-env-ref-type&gt;javax.sql.DataSource&lt;/resource-env-ref-type&gt;
  &lt;/resource-env-ref&gt;
  </code></pre>
  
  <p>And I've added this to my Context by using a context.xml file in META-INF. The Context entry looks like:</p>
  
  <pre><code>&lt;Resource name="jdbc/MyDatabase" auth="Container" type="javax.sql.DataSource"
      maxActive="100" maxIdle="30" maxWait="10000"
      username="username" password="password" driverClassName="com.mysql.jdbc.Driver"
      url="jdbc:mysql://127.0.0.1:3306/mydb?autoReconnect=true"/&gt;
  </code></pre>
  
  <p>I'm using Tomcat 6, MySQL 5, the latest MySQL driver (not the older v3 but the newest v5 driver).  </p>
  
  <p>Update: This is not working for me because I'm using it in a plain-old class. I've created a new project and added a servlet to it. The DataSource is non-null in the servlet.</p>