Discussions

EJB design: DataSource lookup: where to put it ?

  1. DataSource lookup: where to put it ? (2 messages)

    Hi all,
    I have the following question: what's the most correct method for DataSource lookup in a Session Bean? I look it up in the setSessionContext method:

      DataSource ds;

      public void setSessionContext(SessionContext ctx) {
      this.ctx = ctx;
      ds = (javax.sql.DataSource) new InitialContext().lookup ("myPool");
      }

    do you have other suggestions? for example I have read somewhere in this forum to use static-inizializers to populate instance variables of SSB....
    comments?
    thanks
    Francesco
  2. I used a singleton approach...In your bean methods call
    <singleton class>.getInstance() to get the instance and then make a call to a getConnection() method to get the connection.

    This will eliminate the overhead of looking up the data source every time...
  3. I ripped this pattern staight from the Java Petstore:

    I place all my data access code in a helper class which is instantiated by the SessionBean as it is required. The datasource lookup occurs in the constructor of the DataAccess Helper. The helper provides all your database interaction, and extends a generic DataAccess class with some methods for managing connections.

    The advantage of this is that you can use a Factory pattern to instantiate different DataAccess objects for different RDBMS implementations, and you can also have non-database methods in your Session bean and avoid the cost of acquiring a DataSource in the setSessionContect.


    public class SessionBean
    {
      public void myMethod()
      {
        SessionDAO dao = new SessionDAO()
        
        dao.myDataMethod();

      }
    }


    public class SessionDAO extends DataAccess
    {
      private DataSource ds = null;

      public SessionDAO()
      {
        ds = (DataSource) new InitialContext().lookup ("myPool");
        

      }

      public void myDataMethod()
      {
         // get connection
         // do some stuff
         // close connection
      }
    }