N
N
Nikolay Baranenko2017-06-07 08:17:34
Java
Nikolay Baranenko, 2017-06-07 08:17:34

What is the correct way to access JNDI connection of Oracle database?

Hello.
I decided to switch Java servlets from individual JDBC connections to a named JNDI connection, for this I created a context.xml file in META-INF and registered the connection in it

<Context reloadable="true">
    <Resource name="jdbc/Oracle" auth="Container"
              type="javax.sql.DataSource"
              driverClassName="oracle.jdbc.driver.OracleDriver"
              url="jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521)))(CONNECT_DATA=(SERVICE_NAME=oracledb)))"
              username="dbuser"
              password="db123"
              maxActive="150"
              maxIdle="120"
              maxWait="-1"/>
</Context>

then created a method in the class
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.annotation.Resource;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class ManagementSystem {

    public static Connection getConnection() throws SQLException, ClassNotFoundException, NamingException
    {
        Context ctx = new InitialContext();
        DataSource ds = (DataSource)ctx.lookup("java:/comp/env/jdbc/Oracle");
        Connection connection = ds.getConnection();
        System.out.println(connection);
        return connection;
    }

}

when accessing the method, I get the error
Exception in thread "main" javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:
java.naming.factory.initial solve this problem?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question