I'm trying to register a new datasource before the server starts but on lookup execution I'm getting
javax.naming.NameNotFoundException: Name [jdbc/db] is not bound in this Context. Unable to find [jdbc].
This is how I start tomcat:
Tomcat tomcat = new Tomcat();
//...
ContextResource resource = new ContextResource();
resource.setName("jdbc/db");
resource.setAuth("Container");
resource.setType("javax.sql.DataSource");
resource.setScope("Sharable");
resource.setProperty("driverClassName", "org.hsqldb.jdbc.JDBCDriver");
resource.setProperty("url", "jdbc:hsqldb:hsql://localhost:1234/mydb1");
tomcat.getServer().getGlobalNamingResources().addResource(resource);
tomcat.start();
tomcat.getServer().await();
The lookup:
Connection conn = null;
try {
Context initContext = new InitialContext();
Context envContext = (Context) initContext.lookup("java:/comp/env");
DataSource ds = (DataSource) envContext.lookup("jdbc/db");
conn = ds.getConnection();
conn.createStatement()....
} catch (Exception e) {
e.printStackTrace();
}
What am I missing here?
Oh well i figured it out! Instead of adding it in the GlobalNamingResources
I added it in the NamingResources
and it works!
If someone can tell me the difference between globalNamingResources and (local)NamingResources and how to lookup a globalNamingResource then please leave me a comment!
You don't show us how you look up the JNDI resource. However, in any case the full JNDI name to your resource is
java:comp/env/jdbc/db
i.e. that's what you need for lookup.There's further reading here: https://stackoverflow.com/a/4099163/131929