javapostgresqltomcatdatasourcejndi

Working with DataSource and Tomcat JNDI API


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:

  1. Creating Instance of DataSource Class and Setting its Properties

    org.postgresql.ds.PGSimpleDataSource dataSource = new org.postgresql.ds.PGSimpleDataSource();
    dataSource.setServerName("localhost");
    dataSource.setDatabaseName("db01");
    dataSource.setUser("jwi");
    dataSource.setPassword("password");
    
  2. Registering DataSource Object with Naming Service That Uses JNDI 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?

  1. 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.


Solution

  • for the second question, deployed means that your datasource is declared in the context.xml in tomcat. Here is an example of an oracle database (you have to change the driver for postgres) :

    <Resource name="jdbc/myoracle" auth="Container"
                  type="javax.sql.DataSource" driverClassName="oracle.jdbc.OracleDriver"
                  url="jdbc:oracle:thin:@127.0.0.1:1521:mysid"
                  username="scott" password="tiger" maxTotal="20" maxIdle="10"
                  maxWaitMillis="-1"/>
    

    After that, you can code the java part, for that you can watch this link http://www.javapractices.com/topic/TopicAction.do?Id=127

    For a complete example, there's a good tutorial here http://alvinalexander.com/blog/post/java/how-configure-tomcat-dbcp-connection-pool-pooling-postgres.

    Hope this help