Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JNDI and javax.sql.DataSource

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.

I'm using syntax like this in my database class:

@Resource(name = "jdbc/MyDatabase")  
private javax.sql.DataSource dataSource;  

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:

Connection c = dataSource.getConnection();  

And it throws a NullPointerException everytime. I step into this in the debugger and as it turns out, dataSource IS null.

It seems magical and weird that I do not initialize dataSource myself in the code. Any idea what I'm doing wrong?

My web.xml contains the following block to establish the resource:

<resource-env-ref>
    <resource-env-ref-name>jdbc/MyDatabase</resource-env-ref-name>
    <resource-env-ref-type>javax.sql.DataSource</resource-env-ref-type>
</resource-env-ref>

And I've added this to my Context by using a context.xml file in META-INF. The Context entry looks like:

<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"/>

I'm using Tomcat 6, MySQL 5, the latest MySQL driver (not the older v3 but the newest v5 driver).

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.

like image 425
Randy L Avatar asked Mar 01 '23 02:03

Randy L


1 Answers

You need at least to have the following in either the appserver's /conf/context.xml or the the webapplication's /META-INF/context.xml file:

<Resource
    name="jdbc/MyDatabase" 
    type="javax.sql.DataSource"
    driverClassName="com.your.Driver"
    url="jdbc:your://url"
    username="foo"
    password="bar"
/>

Also see http://tomcat.apache.org/tomcat-6.0-doc/jndi-resources-howto.html

And in the webapp's /WEB-INF/web.xml you need to define the following:

<resource-env-ref>
    <resource-env-ref-name>jdbc/MyDatabase</resource-env-ref-name>
    <resource-env-ref-type>javax.sql.DataSource</resource-env-ref-type>
</resource-env-ref>

Edit: I now see that you edited your post to add the coding. I also see that you used resource-ref instead of resource-env-ref. The first refers to an external resource (read: not webcontainer-managed) and the second refers to an internal (environmental) resource (read: webcontainer-managed). Replace it and see.

like image 69
BalusC Avatar answered Mar 07 '23 04:03

BalusC