calling getDBConnection

Discussions

EJB programming & troubleshooting: calling getDBConnection

  1. calling getDBConnection (3 messages)

    I have sevaral EJBs need to access database by calling

    protected Connection getDBConnection(String dsnName) throws javax.ejb.EJBException
    {

    Connection cx = null;
    try {
    // get an EAS connection cache reference
    InitialContext ic = new InitialContext();
    DataSource ds = (DataSource)ic.lookup("java:comp/env/jdbc/myDB");
    cx = ds.getConnection();
    } catch (NamingException ne) {
    log("getDBConnection Naming Exception " + ne,1);
    }catch (Exception e){
    log("getDBConnection Exception " + e,1);
    }
    return cx;
    }

    I want put this function in a separeate class so that every EJBs can call this function to get db connection.
    but,this function look up JNDI by (DataSource)ic.lookup("java:comp/env/jdbc/myDB"),which jdbc/myDB defined in each ejb descriptor.
    what I like is:every EJB call getDBConnection in a class,and define JNDI resource jdbc/myDB only once,not in each EJB's descriptors
    any body tell me how to do this?

    Threaded Messages (3)

  2. calling getDBConnection[ Go to top ]

    You can create a ServiceLocator class based ServiceLocator design pattern,
    http://java.sun.com/blueprints/patterns/ServiceLocator.html
    which will encapsulate your DBConnection. Clients (in your case EJBs) will just request for connection from ServiceLocator.

    raghu
  3. calling getDBConnection[ Go to top ]

    Thank you.
    I was looking at ServiceLocator with a question.I need the ServiceLocator look up the connection pool.so,the ServiceLocator must be a EJB to get resource through EJB descriptor,it's can not be a normal class?am I right?
  4. calling getDBConnection[ Go to top ]

    also,my getDBConnection return a Connection,if I move the function to the serviceLocator(a EJB),does serviceLocator return a Connetion?