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.