Q
Problem solve Get help with specific problems with your technologies, process and projects.

Typecasting the remote interface of EJB

When will I typecast my remote interface of EJB to EJBHome (Remote Home) and when will I typecast it to a Local EJB Home?
Prior to EJB 2.0, the only one way to obtain a reference to an EJB, no matter where the EJB was located, was to execute a lookup for the EJB's remote interface. This produced a lot of unnecessary overhead when accessing the EJB within the same JVM, such as the case when one EJB accesses another EJB.

With the release of version 2.0 of the EJB specification, the local interface was introduced to eliminate the network overhead incurred when accessing an EJB in the same JVM. An EJB can be defined as implementing a local interface, a remote interface, or both.

The primary differences between local and remote EJBs are:

1) The home interface for a local EJB must extend javax.ejb.EJBLocalHome and the home interface for a remote EJB must extend javax.ejb.EJBHome.

2) The bean interface for a local EJB must extend javax.ejb.EJBLocalObject and the bean interface for a remote EJB must extend javax.ejb.EJBObject.

3) The lookup mechanism for a remote EJB includes:
a) Properties passed to the InitialContext constructor
b) Requirement to narrow the home object

The lookup steps are compared in the following examples:

Local interface lookup steps:

InitialContext jndiContext = new InitialContext();
MyEJBLocalHome home =
   (MyEJBLocalHome)jndiContext.lookup("java:comp/env/ejb/MyEJB");
Remote interface lookup steps:
Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY,
        "SomeInitialContextFactoryName");
props.put(Context.SECURITY_PRINCIPAL, "jdoe");
props.put(Context.SECURITY_CREDENTIALS, "foobar");
props.put(Context.PROVIDER_URL, "some://provider.url");
InitialContext jndiContext = new InitialContext(props);
Object objref = jndiContext.lookup("java:comp/env/ejb/MyEJB");
MyEJBHome obj =
   (MyEJBHome)PortableRemoteObject.narrow(objref,
                                          MyEJBHome.class);
Good application frameworks will usually hide the lookup differences between local and remote EJBs in a factory object and expose similar methods for both, as follows:
public EJBLocalHome lookupLocalEJB(String jndiHomeName)
{
   ...
}

public EJBHome lookupRemoteEJB(String jndiHomeName)
{
   ...
}
Your decision to cast to a local interface or a remote interface can now be made in a clean manner within these separate methods.

Dig Deeper on Topics Archive

Have a question for an expert?

Please add a title for your question

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.

Start the conversation

Send me notifications when other members comment.

Please create a username to comment.

-ADS BY GOOGLE

SearchSoftwareQuality

SearchAWS

SearchCloudComputing

TheServerSide.com

Close