get Connection in Session bean from Entity CMP Bean

Discussions

EJB design: get Connection in Session bean from Entity CMP Bean

  1. I have an Entity CMP Bean and Session bean.
    (I use Borland App Server 4.5.1 and JBuilder 5.0)
    In Entity Bean in META-INF\ejb-inprise.xml
    there are connection parameters to database, such as:

    <datasource-definitions>
        <datasource>
          <jndi-name>DataSource</jndi-name>
          <url>[URL]</url>
          <username>[USER_NAME]</username>
          <password>[PASSWORD]</password>
          <driver-class-name>oracle.jdbc.driver.OracleDriver</driver-class-name>
        </datasource>
      </datasource-definitions>

    How to get this connection parameters from Session bean?
    Or how to get java.sql.Connection, obtained in CMP Bean, from Session bean?

    I'm sure, there are methods to get it using JNDI.

    THank you.
    Anton.
  2. Follow the following steps

    1) Get the intial context
       Context ctx = getInitialContext();
    2) Look up the datasource

       e.g DataSource ds = ctx.lookup("DataSource Name");
    3) Connection cn = ds.getConnection();

    U can use this connection now

    Note : U have to implement getInitialContext() method. The code should be ut application server specific
    Gaurav
  3. Hey there.
    The steps in the message above are the standard way. I just wanted to note that getting an initial context is not app server specific. The portable way to do it is the obvious one:
    InitialContext ic = new InitialContext();

    Gal
  4. Hi anton,
      use this code to get connection

    InitialContext initCtx = null;

    try
    {
     initCtx = new InitialContext();

     DataSource ds;

     ds = (javax.sql.DataSource)initCtx.lookup("DATASOURCE JNDI NAME");

     Connection con = ds.getConnection();
    }
    catch(NamingException ne)
    {

    }

    Bye

    Arun Sethia