3 Replies Latest reply on Nov 20, 2006 7:43 AM by jaikiran

    JNDI lookup for Data source

    dasunp

      guys,
      I am reading that when a datasource to be looked up in a EJB project each ejb should have reference-ref defined. My question is if this EJB project has a java file (say.. a utility class) which needs to lookup datasource, where should be the reference-ref defined. Or what is the standard way of looking up datasource in this case whcih is compatible with J2EE (so I can use the same technique whcih works with all app servers)

      Appreciate expert advice from somebody..

      Dasun Perera

        • 1. Re: JNDI lookup for Data source
          jaikiran

          resource-ref are not mandatory but are recommended. If your java utility is being used in a servlet, then the resource-ref will go in the web.xml. If the utility is being used in a EJB then the resource-ref will go in the ejb-jar.xml. In either case, the java utility code will not change. Your code will look like:

          Context ctx = new InitialContext();
          ctx.lookup("java:comp/env/.......");



          • 2. Re: JNDI lookup for Data source
            dasunp

            appreciate your comments.. few more clarifications..

            this utility class is in EJB project. As I read resource-refs can only be placed per each EJB (only specific to a particular EJB/s) There is no way a genral resource-ref can be defined in ejb-jar.xml. If so, this resource-ref will only be visible to only EJBs where resource-refs are defined. So how a utility class in a EJB project looks up such a resource-ref?

            When looking up such resources, out of the following two way which is the best practise?

            lookup gicing full path
            ctx.lookup("java:comp/env/something/something");

            or
            lookup giving only relative path
            ctx.lookup("something/something");

            • 3. Re: JNDI lookup for Data source
              jaikiran

              You are right, the resource-ref are mentioned per EJB. But those resources can still be used across EJBs. I think this is determined by the res-sharing-scope(which can take values 'Sharable' or 'Unsharable') attribute inside the resource-ref element. The dtd will provide more details. By default this value is Sharable which i guess means that the resource can be accessed across the EJBs.


              When looking up such resources, out of the following two way which is the best practise?

              lookup gicing full path
              ctx.lookup("java:comp/env/something/something");

              or
              lookup giving only relative path
              ctx.lookup("something/something");


              The second one is not going to work. When you specify a resource-ref, the objects will be bound in the java:comp/env namespace. So unless you specify that prefix, the lookup code will not be able to retrieve that object for you.