Getting your E J and B’s right

J2ee is a collection of programming standards, innovations, concepts and strategies all written in the Java language. With EJB, which is a vital part of J2ee, you can quickly build scalable, robust, distributed, portable, secure and reliable server side components.
Server side components are distributed business objects (these objects can be physically separated as per their utility) that encapsulate business logic.
Server side components being object oriented are reusable, extensible and flexible.
EJB components can be ported across any EJB compliant application server that supports the EJB model avoiding locking into any vendor’s solution. This gives the EJB component designer the option to scale to other EJB compliant application servers if required. Thus the EJB components are independent of the implementation of the EJB Server.
Middleware services for server side components is handled by the Application Servers that support large user populations in mission critical systems and handle resources, concurrency, transactions, security, persistence, load balancing and distribution of objects automatically, allowing the application developer to focus on business logic.
EJB is basically consists of a set of specifications to be followed by EJB Application Servers and a set of interfaces to be implemented by Server side components and application servers.
J2EE is one of three different platforms:
J2ME: Java 2 Micro Edition
A restricted form of the Java language.
J2SE: Java 2 Standard Edition
Standard services for servlets and applets. The JDK that most people are familiar with.
J2EE: A complete server side platform for enterprise class applications.
J2EE provides the following APIs to application programmers:

Ø EJB specification
Ø RMI-IIOP: J2EE needs Java’s language of communicating with remote distributed objects.
Ø Java Naming and Directory Interface
Ø Java Messaging Service
Ø Java Transaction API
Ø Servlets
Ø JSP pages
Ø Java Mail
Ø Java API for XML parsing

EJB technology is based on two important technologies:

JNDI and RMI-IIOP

JNDI is Java’s de facto mechanism for performing simple, powerful networking.
RMI-IIOP replaced RMI to provide compatibility with CORBA.
RMI-IIOP allows an object distributed across a network call a method on another object residing elsewhere on the network using a procedure called Remote Method Invocation.

Marshalling and Unmarshalling

Primitive types as well as objects can be transferred across a network using RMI. To ensure compatibility of data transferred between heterogeneous environments, parameters are marshaled at one end and unmarshalled automatically at the other end by Java and RMI-IIOP.
RMI-IIOP supports both passing by value (passing a copy of the variable) as well as passing by reference (passing a reference to the variable).

Distributed object architectures are based on a network communication layer that contains of an object server, a skeleton and a stub.
The object server and the skeleton reside on the middle tier while the stub resides on the client side.
The object server is the business object (in EJB parlance: the bean class).
The skeleton listens to requests from the stub.
The stub acts as a proxy and passes on requests from the stub to the object server via the skeleton.

Note that this process is generally taken care of by the application server and is part of the middle ware services it provides.
When using RMI-IIOP you need to create a remote interface that exposes all the beans business methods.
All java basic primitives are passed by value when methods are called remotely.
If you want to pass an object over the network by value it must be serializable.
If you want to pass an object over a network by reference it has to be a remote object and has to implement java.rmi.Remote.

JNDI

JNDI is the de facto mechanism by which java locates objects anywhere across a network. Internally a directory has a tree structure.
A directory service can be looked upon as a scaled down version of a database.
JNDI is a bridge over naming and directory services.
It is a good idea to cache an initial context for future use instead of creating it when required.
Relation between JNDI and RMI-IIOP
An RMI-IIOP server first registers itself using JNDI.
A client then looks up this server using its JNDI name.
Enterprise Beans are server side components that are distributed over a multi-tiered, distributed environment.
Session beans model business logic while entity beans model business data. A message bean typically contains message-oriented logic.
Constituents of an Enterprise Bean
The Enterprise Bean class:
All entity beans must implement the javax.ejb.EntityBean interface, which in turn implements the javax.ejb.EnterpriseBean interface, which in turn extends java.io.Serializable.
All session beans must implement the javax.ejb.SessionBean interface which also extends the javax.EnterpriseBean interface.
When a client wants to invoke a method on a bean class, it does not do so directly, rather the request is intercepted by a container class called the EJB Object, which then delegates it to the bean instance.
By intercepting the client call, the container can perform middleware activities effectively.
The container generates the code for the EJB object automatically.
The Remote Interface:
All remote interfaces should extend from javax.ejb.EJBObject which extends java.rmi.Remote.
All methods in a remote interface throw a remote exception.
The Home Interface:
Just like the EJBObject the EJBHome object from which the home interface is derived is container generated.
All home interfaces extend from javax.ejb.EJBHome, which derives from java.rmi.remote.
All methods in the home interface throw a create exception in addition to a remote exception.
The remote and the home interface indirectly extend from the rmi.remote interface, which implies that they are fully networked rmi objects.
The deployment descriptor:
To declare the middleware service requirements of your component to the bean container you must configure the deployment descriptor (usually the ejb-jar.xml).
Some of the requirements you could declare may be
Persistence
Security
Transaction control
Lifecycle management
By having a deployment descriptor you can migrate to another ejb environment without changing source code.
There may be other xml files, text files or binary files to configure the container specific requirements of your component, which may vary with the container.
After creation of all files they may be packaged into an ejb.jar file ready for deployment in the web server container.
Note: the home interface and the remote interface are network aware because clients use them across a network. Hence they need to extend from the java.rmi.remote interface.

Q:
In case create methods are system defined, how come we can create different create () methods with different signatures?
A:
One doesn’t write any code into the create methods of the home interface, one just defines them and leaves them blank.
Now the Home interface extends EJBHome so when rmi compiler is run on this home interface, it figures that there’s one (or more with different signatures) create methods that need to have equivalents in the stubs that are generated.
The create methods of the generated stubs contain logic to marshall the parameters and transport them over the network.
Its okay to create different create methods with different signatures. The rmi compiler creates the equivalent create methods in the stubs (which has the serializing marshalling logic).

ejbCreate (for session ejb) optional
ly contains logic(user written) in a bean. It gets executed when the corresponding create () method of the home interface is executed by the client code.

ejbCreate (for Entity ejb)For a CMP bean this method is called just prior to insertion of a row into the database. Here the developer can perform actions such as initialization of fields to be inserted, etc.
For a BMP bean the bean developer has to code the logic to enter a row into the database inside the ejbCreate() method.

The ejbCreate() is invoked before the new record is created. ejbPostCreate is called after the new record is inserted. The primary key is initialized and the remaining fields are set to null when the new record is inserted using CMP.
When the setFoo() method is called the remaining fields are updated from NULL to the value specified in the parameter.

ejbPostCreate (for Entity ejb) contains actual logic in a bean. This may be code for getting a handle or getting the primary key and then doing something useful with them. The difference is that the logic is executed after the create (row insertion) happens.

The ejbFindByPrimaryKey() contains logic(user written for BMP beans and machine generated for CMP beans : behind the scenes) that looks like
Select * from table where prykey1=“doo” and prykey2=”bar”;

More about the primary key class:

The primary key class is just a simple java class, which has a set of properties that have a one to one correlation with the primary key columns of the relevant table.
So the ejbFindByPrimaryKey() should be accepting a primary key as a parameter, retrieve values of each of the properties by retrieving the relevant row from the database. In case of CMPs all this is container generated while in BMPs they have to be handwritten.
The hashcode() and equals() methods are just regular methods for primary key classes.

Object Serialization:
Q:
What is the difference between serialization and persistence?
A:
Serializable: Enables the conversion(back and forth) of java objects into bit-byte blobs (series of 1s and 0s) that can can be transmitted over a network or stored to disk. It’s mostly used in Object Streams, sockets, RMI, temporary storage (like activaton/ passivation of beans,etc)

Persistence: means saving data (objects or primitive values) to storage. This may include serialization for the purposes of storage. This may include serialization for the purposes of storage (but for the purposes of transmission over a network)
Usually however persistence means storage to a database (usually an RDBMS).

The Remote Interface:
Extends javax.ejb.EJBObject
The remote interface is accessed using RMI-IIOP and hence every method it has needs to throw a java.rmi.Remote exception.
The same method in the bean has only one other difference in it’s signature in that it does not throw the remote exception.
The Home Interface:
The home interface extends javax.ejb.EJBHome.
It has a create method which throws a remote exception as well as a create exception.
The Bean class:
The bean class needs to implement server call back methods in addition to the business methods.
A session bean needs to implement javax.ejb.SessionBean while an entity bean implements javax.ejb.EntityBean
The ejbActivate and ejbPassivate methods do not apply for stateless session beans and hence they are left empty.
Any resources that need to be cleaned up should be included in the ejbRemove method.
The Deployment Descriptor:
tag specifies the common name of the entity bean.
The tag gives the fully qualified class name of the home interface.
The tag gives the fully qualified class name of the remote interface.
tag specifies the fully qualified name for the bean class.
only applies to session beans and specifies whether it is a stateless or stateful session bean.
There may be other vendor specific files or a GUI to make configurations specific to the application server you are using.
The ejb-jar.xml must always be placed in the meta-inf folder while creating the ejb-jar file.
When you build the ejb-client.jar only those interfaces, helper classes and stubs needed by the client should be included.

EJB Callback methods

ejbCreate()
(for stateful session beans)
can have one or more ejbCreate() methods with or without parameters.
These parameters can be used to initialize instance variables.
Must have at least one ejbCreate() method.
(for stateless session beans)
Only one empty ejbCreate method with no arguments

Instance pooling:
To conserve memory resources session beans are pooled. In case of stateless session beans, they are simply destroyed when not required and recreated when more instances are required.
However for stateful session beans instance pooling is not efficient as the state of the bean has to be preserved/ restored before they can be added/ removed from the pool.

Activation and Passivation:
The conversational state of stateful session beans is serialized to a permanent storage device during passivation and this state is retrieved during activation.
Activation and passivation may be necessary to conserve system resources.
Activation and passivation is not necessary for stateless session beans as there is not state to be conserved. They can simply be created or destroyed as required.

ejbPassivate()
(for stateful session beans)
This must contain code to relinquish resources used by the session bean such as socket connections.
(for stateless session beans)
left empty as there is no conversational state

ejbActivate()
(For stateful session beans)
acquire resources required
(for stateless session beans)
left empty as there is no conversational state

getEjbObject()
method is useful in the case of session beans and you want to call another bean and a pass a reference to your original bean.

ejbRemove()
This method is called just before the bean is destroyed and must contain code to relinquish system resources no longer required.
The home interface has no corresponding remove () method; it inherits this method from it’s superclass the ejbHome object.

Entity Beans

Entity beans can be made persistent using various methods including serialization.
The primary key class should be serializable.
ejbLoad()
Called after data is loaded into into the entity bean
ejbStore()
Called before data is stored to permanent storage. (Made persistent)

An entity bean can also be activated, passivated.

Before the instance is returned to the instance pool after dissociating itself from its client (passivation) ejbPassivate() is called and this must contain code to release resources such as sockets, connections, etc

Before the instance is retrieved from the instance pool for servicing a client it has to retrieve all necessary resources required.
This is done in the ejbActivate() method.

There are two types of persistence: BMP and CMP.

The ejbCreate() method is called just before data is entered into the database.
The ejbDestroy() method is called before the data in the database is destroyed. This method is left empty in CMP beans.

For each create () method in the home interface you need a corresponding ejbCreate() method in the bean class.

The home interface may have a method
public Authors create() throws CreateException, RemoteException.
The bean class should have a corresponding method:
public AuthorsKey ejbCreate() throws…
Note that the create method in the home interface returns a bean type whereas the create method in the bean class returns a primarykey type.
Similary the findByPrimaryKey() method returns a bean type in the home interface whereas it returns a primarykey type in t
he bean class.
This is because the bean class interacts with the client via the container while the home interface is a networked object, which can be directly called by the client.
An entity context identifies the environment of the bean.

The Remote, Home, javax.ejb.EnterpriseBean, javax.ejb.EntityBean, javax.ejb.SessionBean, javax.ejb.EjbObject, javax.ejb.EjbHome are interfaces.
The PrimaryKey, Bean, are classes.
java.io.Serializable is an interface.
java.rmi.Remote is an interface.
The remote interface extends javax.ejb.EjbObject
The home interface extends javax.ejb.EjbHome
The Bean class implements either javax.ejb.EntityBean or javax.ejb.SessionBean.
The primary key class implements java.io.Serializable.

For primitive values as pry keys, a separate pry key class is not required.
Consider the primary key is a primitive String.
The find method in the home interface looks like
public Vorgeleg findByPrimaryKey(String key) throws FinderException, RemoteException

In the bean class the find method looks like
public String ejbFindByPrimaryKey(String key)
The create method looks like
public String ejbCreate(String key)
key is the primitive primary key for that bean.

If the primitive key is compound, create a primary key class say VorgelegKey
The find method in the home interface looks like
public Vorgeleg findByPrimarykey(VorgelegKey pk) throws FinderException, RemoteExcepion

In the bean class the find method looks like
public VorgelegKey ejbFindByPrimaryKey(VorgelegKey key)
The create method looks like
public VorgelegKey ejbCreate(String arg1,int arg2,int arg3)
These arguments are the primary keys for that bean.

In addition to the findByPrimaryKey method the home interface may contain any number of custom defined finder methods. These need to be configured while deploying and in vendor specific.

create() in an entity bean has an entirely different meaning in entity beans as compared to session beans.

The create() method of the home interface inserts a primary key value into the database and initializes all the other table attributes to be null (which means the fields other than the primary keys should be able to accept null values- default NULL) whereas setter methods are used to update the remaining fields in the database. (equivalent to a jdbc update)

The create method of the session bean on the other hand is involved with the association of a bean client with a session bean instance.

The java.lang.reflect.UndeclaredThrowableException is usually just a mask for some other exception inside it. In the stack trace the actual exception thrown is available.

All arguments into the methods of the remote interface should extend serializable. Database connections, resultset, etc are not serializable and hence cannot be marshaled/ unmarshalled across a network.

Usually stateless session beans are used to access data that is more or less static that might be read only.

Updates and inserts are done via entity beans, which have better container managed middleware services such as transactions and rollbacks.

About cuppajavamattiz
Matty Jacob - Avid technical blogger with interests in J2EE, Web Application Servers, Web frameworks, Open source libraries, Relational Databases, Web Services, Source control repositories, ETL, IDE Tools and related technologies.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: