In "Mastering EJB II", p. 147, the getConntection() method has the following lines:
Context ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup("...");
Why use a "new InitialContext()" instead of the ctx class variable initialized via the setEntityContext() method?
You can use that too.....
They are different things.
The Initial context provides the root of the JNDI directory structure. To do look ups from here you have to use the fill JNDI name of the deployed component.
SessionContext, EnitiyContext etc are interfaces that provied access to the contract between the bean and the container. Part of this contract is the environment context which allows the look up of ejbs and properties that are mapped in the ejb-jar.xml deployment descriptor for individual ejbs,
But arguably most importantly the EntityContext allows you to manage declarative transaction control.
As David said, these object relate very narrowly. They handle very different aspects of the beans interactions with its environment.
The Scupper Group
But is creating a new InitialContext not an expensive operation (I'm just guessing here, e.g. reading in jndi.properties or something similar, looking up the JNDI service, etc.)?
If you already have a SessionContext, wouldn't it be "cheaper" to use that one?
The issue is you CANNOT use the SessionContext to do the same things you do with the InitialContext. They are not the same thing. Its like saying I need a car to drive a thousand miles, but they are too expensive so I'll just use an orange.
javax.ejb.EJBContext --> javax.ejb.SessionContext
A SessionContext *is not* an InitialContext. The only thing they have in common is they both happen to use the word Context. For example, how would you do a lookup() operation on a JDBC cache using the SessionContext? Or how would you cause a rollback in a CMT bean using the InitialContext?
In answer to your expense question, in most cases no, this is not expensive in the least. The call
InitialContext ctx = new InitialContext() normally simply checks a system property of the that vendors InitialContext Singleton and returns you a reference to that. The only 'expense' is instatiation of the abstract.
The Scupper Group
dave at scuppergroup dot com