I'm trying to understand establishing a database-connection with a DataSource Object
and the JNDI API
.
I'm working with Intellij UE and have a local Tomcat-8
- and Postgres-Server
running.
I proceed as mentioned in the Oracle Java Documentation:
Creating Instance of
DataSource Class
and Setting its Propertiesorg.postgresql.ds.PGSimpleDataSource dataSource = new org.postgresql.ds.PGSimpleDataSource(); dataSource.setServerName("localhost"); dataSource.setDatabaseName("db01"); dataSource.setUser("jwi"); dataSource.setPassword("password");
Registering
DataSource Object
with Naming Service That UsesJNDI API
Context ctx = null; try { ctx = new InitialContext(); ctx.bind("jdbc/localDB", dataSource); } catch (NamingException e) { e.printStackTrace(); }
The Oracle Documentation says:
With the properties set, the system administrator can register the BasicDataSource object with a JNDI (Java Naming and Directory Interface) naming service.
So my first Question is: What means to register a DataSource
? Is my code obove already the registration of an DataSource Object
to JNDI
?
Using Deployed
DataSource Object
try { Context ctx = new InitialContext(); DataSource ds = (DataSource) ctx.lookup("jdbc/localDB"); dbCon = ds.getConnection(); ...
In this code cutting IntelliJ always claims, that it can't resolve the method getConnection()
.
The Oracle Documentation says:
After a basic DataSource implementation is deployed by a system administrator, it is ready for a programmer to use.
So my second Question is: What exactly means deployed in this case? Creating a DataSource Instance
and execute the registration with JDNI
? Or does deployed mean the Tomcat
context.xml
and web.xml
configuration (Tomcat 8 JNDI How-To)?
I'd really appreciate if anybody has a good step by step instruction for this issue, in fact that the Oracle Documentation isn't really clear about some points imho.