Discussions

EJB design: How do I pass environment information to an EJB instance

  1. I have an EJB that performs some calculations from values retrieved from some database. The logic for performing the calculations are the same though the values are retrieved from different databases. One of the database is the Employee database and the other one is the Contractor database. Since the calculation logic is the same, my approach is to bind the same EJB classes to 2 different JNDI names, namely EmployeeCalculatorEJB and ContractorCalculatorEJB.

    Now, I need to pass a different Datasource object to each of these beans so that they read from the relevant database (ie either Employee or Contractor database). How do I pass these types of information such that the beans are able to know whether they should read from which Datasource?

    rubberben
  2. Let me elaborate further. I created 2 session bean entries in ejb-jar.xml though using the same EJB classes. Furthermore, I bind it to different JNDI names.

    rubberben


  3. Use the resource reference element in the ejb-jar.xml.

    Define the SAME resource reference in both ejb's
    <resource-ref>
      <description>Connection Pool</description>
      <res-ref-name>jdbc/paidworkerDB</res-ref-name>
      <res-type>javax.sql.DataSource</res-type>
      <res-auth>Container</res-auth>
    </resource-ref>

    And then bind this same name (jdbc/paidworkerDB) to the respective JNDI name of each different database connection pool.



    Otherwise, set some environment variable:
    <env-entry>
      <env-entry-name>someName</env-entry-name>
      <env-entry-type>java.lang.String</env-entry-type>
      <env-entry-value>employeeDB</env-entry-value>
    </env-entry>

  4. Hi,

    Won't there be a JNDI naming conflict if EmployeeCalculatorEJB and ContractorCalculatorEJB refers to different datasources within the same container?

    Ben
  5. I don't think that you will have JNDI problems. it is only a matter that you will have two different DataSources bound to two different JNDI. as the guys mentioned to you in the deployment Descriptor, you define to the Bean which one it should get its data from.

    Moreover, you need to define those DataSources in your Application Server, in case of Weblogic, you define two different Databse Pools, one for Employee and the other for the Contractor. Even if these two Database are in two different IPs, Weblogic will able to manage these pools and creat them to you while Server start up.