Search code examples
javatomcatjdbcapache-tomee

Using JDBC datasources from context.xml in TomEE


TomEE is a great project, combining the lightweight experience of Tomcat with Java EE features. I have many JDBC datasources declared in context.xml, but when I want to use that Datasource via JNDI I get an Exception. So how can I get working a JDBC datasource declared in context.xml in TomEE

My datasource declared in context.xml

 <Resource auth="Container" 
        name="local_jdbc_db"  
        type="javax.sql.DataSource" 
        driverClassName="com.mysql.jdbc.Driver"  
        url="jdbc:mysql://localhost:3306/mydb" 
        username="user" 
        password="pass"      /> 

The code to get the Datasource from JNDI

Context contextoInicial = new InitialContext();
Context contexto = (Context) contextoInicial.lookup("java:comp/env");
DataSource ds= (DataSource) contexto.lookup("local_jdbc_db");

Solution

  • UPDATE Just to anyone having this rare problems with TomEE: I tried creating datasources in context.xml and deploying in TomEE JAX-RS version 1.5.0 with no luck, it always throws me null pointer exceptions and datasource name not found. Recently I tried the same with TomEE JAX-RS version 1.6.0: I created my datasource in context.xml and create a simple servlet with this code

         Context initContext = new InitialContext();
         Context envContext = (Context) initContext.lookup("java:/comp/env");
         DataSource dataSource = (DataSource) envContext.lookup("jdbc_northwind");
         try (Connection conn = dataSource.getConnection(); 
               Statement s = conn.createStatement();
               ResultSet rs = s.executeQuery("select * from customers")) {
               while (rs.next()) {
                    out.print(rs.getString("CompanyName"));
                    out.print("<br>");
               }         
           } 
    

    ... started the server and Hooray !!!! It shows me results!, but I was a bit was disappointed because when I redeployed the application it shows me the old exceptions (DataSource not found, null pointer exception) So I tried the last thing: register the datasource in web.xml

      <resource-ref>
            <res-ref-name>jdbc_northwind</res-ref-name>
            <res-type>javax.sql.DataSource</res-type>
            <res-auth>Container</res-auth>
            <res-sharing-scope>Shareable</res-sharing-scope>
        </resource-ref> 
    

    And restart the server and... It works, redeploy the application and works very fine!, But this behaviour is quite strange: in Tomcat I never declared my datasource in web.xml and I have no problem with datasources. Maybe a bug?

    UPDATE: Confirmed is a bug, seems like it will be solved for TomEE 1.6.1 UPDATE 2: Solved in TomEE 1.7.0