JNDI (Java Naming and Directory Interface) is a standard Java API that provides a naming and directory service for Java applications. Its purpose is to provide a way for Java applications to store and retrieve objects in a hierarchical naming environment, and to locate and access services via a naming system.
When it comes to JDBC, JNDI is commonly used to obtain a JDBC datasource, which is a connection pool of preconfigured database connections that can be reused by applications. Instead of hardcoding the database connection information, applications can use JNDI to look up a datasource that has been configured by the application server or container. This allows for easier management of the database resources and can help to reduce maintenance and development time for complex applications.
Hereβs an example of how JNDI can be used with JDBC to obtain a datasource:
Context initContext = new InitialContext();
Context envContext = (Context) initContext.lookup("java:/comp/env");
DataSource datasource = (DataSource) envContext.lookup("jdbc/myDB");
Connection connection = datasource.getConnection();
In this example, the InitialContext object is used to obtain a reference to the JNDI context, and then the environment context is looked up where the datasource is registered with the name "jdbc/myDB". When a datasource is obtained in this way, the application does not need to worry about the details of how to create or manage the database connections. Instead, it just uses the datasource to obtain a database connection whenever it needs one.
Overall, JNDI makes it easier to manage and locate resources in a Java application, and when used with JDBC, it simplifies the process of obtaining connections to a database.