How to connect a Java application to the database using JNDI?

I use the JNDI concept to connect to the database. I googled to get the starting point, but did not understand.

What I want to do is a simple standalone java application that uses the JNDI concept to connect to a database.

An example of the source that I have:

DataSource dataSource = null;

Context context = null;





    try {       

        context = new InitialContext();

        dataSource = (DataSource) context.lookup("database_connection");
        }

    catch (NamingException e) {

            System.out.println("Got naming exception, details are -> " + e.getMessage());

        }

Now where do we define database_connection? This is defined in the xml file, and if so, where will we specify it and what format?

If any pointers could be provided, that would be great.

thank

+4
source share
2 answers

, Java. , Java EE. , JNDI DataSource .

JNDI, DataSource, JNDI factory (, InitialContextFactory). Java EE . Java- , .

- factory:

public class MyContextFactory implements InitialContextFactory

JNDI :

System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "mypackag.MyContextFactory");

ObjectFactory getInitialContext, ObjectFactory DataSource (, , ) getConnection().

, . JDBC, , DataSource. Spring, ( Spring, JNDI ).

, factory , - JPA-, Java EE, ( , ). .

, , Java EE, , , DataSource ( Spring, ).

+3

- (LDAP)? , JNDI ( , ) .

+1

Source: https://habr.com/ru/post/1546333/


All Articles