Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

EJB and Resource references

 
Dave Coombes
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I am hoping someone can shed some light on the following behaviour. I am using Websphere 4.0, although I'm not sure if this is relevant.
I have a session bean (SB1) which needs to reference a DataSource so I add a resource reference in its deployment descriptor, say jdbc/MyDataSource which I then map at deployment to the JNDI name jdbc/DS1 of a real datasource.
Similarly I have a session bean (SB2) which also needs access to a DataSource so I add a reference in its DD to jdbc/MyDataSource and at deployment map this in JNDI to jdbc/DS2.
In SB1 and SB2 I look up the datasource using java:comp/env/jdbc/MyDataSource and the correct real datasource is returned to each bean.
I then decide that I would like to move the data access logic to a separate Data Access Object (DAO) (as described in the J2EE Core Patterns). I then have to decide how to look up the DataSource in the DAO (I know I could look the datasource up in the EJB and pass it in).
I create a new InitialContext in the DAO for each call and do a lookup using java:comp/env/jdbc/MyDataSource. To my surprise this worked. More surprising to me was that it would return the correct datasource depending on if SB1 or SB2 was calling it. Even more surprising was that if I cached the InitialContext in the DAO, (i.e. create it when the first call is made, either by SB1 or SB2 and then use that context for all subsequent calls) it still finds the correct datasource.
The same is true for EJB references.
This would imply that the naming context, or something related to it is being carried by the calling thread. Is this the case? The behaviour I see is exactly what I want, especially in the situation where I have an EJB calling a method in a class which subsequently looks up another bean and calls a method on it, as it allows the class to be reused, with the target bean being configurable via the calling beans DD.
I hope this explanation is clear enough for someone to tell me if this is expected/reliable behaviour.
All comments much appreciated.
Cheers
Dave
 
Kyle Brown
author
Ranch Hand
Posts: 3892
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, this is as you expect. It is carried along exactly as transactions are carried along -- in fact it's all based on the thread that is running, which gets associated with the EJB.
Kyle
------------------
Kyle Brown,
Author of Enterprise Java (tm) Programming with IBM Websphere
See my homepage at http://members.aol.com/kgb1001001 for other WebSphere information.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic