Simplifying ejb development with ejb3.0 ----- by debu panda (transfer from TSS) October 2004
Discussion
Enterprise JavaBeans (EJB) was introduced for building distributed components. When it arrived it came with a promise to solve all issues and complexities of CORBA. EJB being the heart of J2EE went through several major revisions and got fattened with many features. Early on, most of the developers fell in love with EJB and used EJB in their application even it did not make any sense. "Blame it on EJB" has been the attitude for many developers when their projects did not scale well and they used EJB.
Development of EJB was never easier and it became more complex with every release of EJB specification. EJB has been compared with an elephant due to its complexity and heavy weight nature. Many developers feel EJB is like an extra layer of sugar syrup on a doughnut. In an age where low carb and Atkins diet is craze, the EJB expert committee has no option but to produce a low carb incarnation of EJB thus simplifying the development of EJB. EJB 3.0 expert committee released a sample picture of the lightweight model during JavaOne 2004 When IT Annuded Release of First Public Draft of EJB 3.0 Specification.
At the first glimpse the new model for EJB looks pretty and in this article we will discuss how EJB 3.0 is trying to dress up in a smaller size pretty outfit to make it appealing for developers. In a follow up article we will discuss how EJB 3.0 IS Simplifying The Persistence Model.
Cleaning Up the dirty laundry
Let Us Look at the ComplexIns in The Current EJB Model Before We Dove Discussing The Details What EJB 3.0 is Bringing on to the table.
The current EJB model requires creation of several component interfaces and implementation of several unnecessary callback methods. The component interfaces require implementation of EJBObject or EJBLocalObject and handling of many unnecessary exceptions is required. The EJB deployment descriptor is complex and error prone. The container managed persistence being based on the EJB model is again overly complex to develop and manage. There are several basic features missing such as a standard way to define a primary key using database sequence and EJBQL is very limited. EJB components do not look like its Object Oriented as it has restrictions for using inheritance and polymorphisms. One major drawback of EJBs is that you can not test EJB modules outside an EJB container and debugging an EJB inside the container is a nightmare for developers. If you used EJB you know the complexities of looking up and INVOCATION OF EJB. IT APPEARS That You Have to Know Minute Details of Jndi To Just Use an ejb in your application.simplifying developers view
If you developed an EJB with the latest specification you realize how difficult is develop a simple EJB like HelloWorld EJB. You need at least two interfaces, a bean class and a deployment descriptor. Most of the developers wondered why do I need all these. IDEs like Oracle JDeveloper, Eclipse and XDoclet made the life simple for developers for doing these mundane tasks however still it was the responsibility of developer to compile these classes and package the deployment descriptor before the EJB can be deployed in your container of choice.
EJB 3.0 IS Trying to Address the complexities by:
Removing need of interfaces and deployment descriptors and these may be generated by the container using metadata annotations Use regular Java classes as EJBs and regular business interfaces for EJBsMetadata Annotations
EJB 3.0 depends heavily on metadata annotations. Metadata annotation being standardized under JSR 175 and will be part of J2SE 5.0. Annotation is a kind of attribute oriented programming and similar to XDoclet. However unlike XDoclet that requires pre-compilation, annotations are compiled into the classes (depending upon what the @Retention is set to) by the Java compiler at compile-time. in developer's point of view, annotations are modifiers like public and can be used in classes, fields, methods, parameters, local variables, constructors, enumerations and packages.You can use annotations in your Java code by specifying attributes that can be used for either generating code, documenting code or providing special services such as enhanced business-level security or special business logic during runtime. The goal of J2EE 1.5 ( 5.0 IS To Simplify Development Using Annotations and Hence It Will Come Up with ITS Set of Annotations. Annotations Are Marked with @ as Follows:
@Author ("Debu Panda")
@Bean
Public class mysessionBean
THE GoAL OF EJB 3.0 IS To Simplify Development and Hence Use Metadata Annotations to Generate Several Artifacts Like Interfaces and Use Annotations INSTEAD OF Deployment Descriptors.
Using Pojos and Pojis
In canonical terms, JavaBeans and interfaces often referred as Plain Old Java Objects (POJOs) and Plain Old Java Interfaces (POJIs) respectively. The EJB class and interface will now resemble POJO and POJI respectively. The requirement of the unnecessary artifacts like home interface is being removed.The developer has to either implement one of the EJB interfaces (SessionBean, EntityBean or MessageDrivenBean) in javax.ejb package or use annotation in the bean implementation class. You can either use Stateless, Stateful, MessageDriven or Entity to annotate your bean Class. for example, if you define a stateless ejb as helloworld you define the EJB As Follows:
@Remote
@StateLess Public Class HelloWorldbean {
Public String Sayhello (String S)
{System.out.println ("Hello:" s;}
}
The interfaces for EJBs either remote or local do not have to implement EJBObject or EJBLocalObject. You have to either supply the business interface for your EJB and implement that interface in your bean class or have it generated during the deployment. Interfaces are optional for Entity beans however required for SessionBean and MessageDrivenDriven. If you do not implement an interface for your session bean, a bean interface will be generated for you. The type of generated interface either local or remote is dependent on the annotation you used in the bean class. If You Look at the Above Code Example, It is very clear what @Remote IS Used to generate a remote interface for the helloworld bean. if Needed, You May Have Both Remote and Local Interfaces for your ejb.
From the above example, it is very clear that the developer do not have to a lot of mundane tasks such as defining interfaces and implementing callback methods.The name of the generated interface is derived from the name of the bean implementation class. Generated interfaces are Well and Good for Developers. However, i do not see any benefit of get.
This is not clear from the draft what is client side requirement for EJB lookup and it is not clear, how do we get hold of these interfaces those are required to invoke this EJB I will recommend against using a generated interface for few reasons?:
The name of generated interface will be derived from the bean name You may not be willing to expose some methods in the EJB in the interface and the generated interface may expose all methods by default. You need the interface at the client side to invoke the EJB .
Removing Need for Callback Methods
EJB 2.1 and prior releases required implementation of several lifecycle methods such as ejbPassivate, ejbActivate, ejbLoad, ejbStore, etc. for every EJB even if you do not need those. For example, ejbPassivate is not required for a stateless session bean still you require to implement that method in your bean class. As EJB 3.0 now resembles regular Java classes implementation of these lifecycle methods have been made optional. If you implement any callback method in the EJB then container will invoke that method.
The only exception is the ejbRemove method in Stateful Session bean where you can use Remove annotation to annotate a Stateful session bean business method. If you use of this annotation it will hint the container to remove the Stateful session bean instance after the completion (normal or Abnormal) of the annotated method. for example, you can specify the following to remove a stateful session bean instance after checkout method is executed. @ Stateful Public Class Cart {
...
...
@Remove public void checkout () {
...
}
}
Annotations vs. Deployment Descriptors
As we discussed earlier deployment descriptors will no longer be required for EJBs and annotations will be used instead. The default values for each attribute in the deployment descriptor will be chosen and developers do not have to specify these attributes unless they want a value other than the default value. These can be specified using annotations in the bean class itself. The EJB 3.0 specification is defining a set of metadata annotations for use by developers such as bean type, type of interfaces, resource references, transaction attributes, security, etc. for Example, IF WE Want To Resource Reference for a Particular EJB THEN WE WILL Define As Follows:
@Resource (name = "jdbc / oracleds", resourcetype = "javax.sql.datasource")
J2EE vendors such as Oracle, BEA, IBM will add annotations for attributes in their vendor specific deployment descriptors and developers will use these to avoid using deployment descriptors. This looks very attractive for developers as the nasty XML descriptors they hated most gets out of their way But this Introduces Few Problems and we need to be careful before embracing annotations.
This defeats the goal of portability of applications because if an EJB uses a vendor specific deployment descriptor this can not be just changed without having to recompiling / repackaging the EJBs. The deployment descriptors provided a holistic view of EJB modules to the assembler / deployer (ejb- jar) without having to look at individual the EJBs and they tweaked these as per the deployment requirement and if descriptors are not available or not generated until the end of deployment this could be a nightmare for them. Deployment descriptors were used by the tools to identify the EJBs in an EJB module and were very useful when you try to migrate from one container to another.EJB 3.0 spec also proposes a way to override the annotations in the deployment descriptors. However details of overriding annotations is missing in the specification.There is NO Doubt That Getting Rid of Deployment Descriptors Will Make The Life Easier for New Developers But this May Become a Management Nightmare IF N OT used carefully.
Simplifying container managed personistence
CMP entity bean is getting a major overhaul in EJB 3.0 to make it compelling for developers. Persistence frameworks like OracleAS TopLink, open source Hibernate have become darling of developing persistence framework for J2EE applications that has disliked Entity beans for its complexity and heavyweight in nature. EJB 3.0 is adopting a lightweight persistence model like TopLink and Hibernate to simplify the container managed persistence and this sounds compelling for developers. Let us do a quick look on the plans for entity beans and we will discuss about the details of the persistence improvement in another Article.
Entity beans are being reincarnated as POJOs and there will be no component interfaces required for entity beans Entity beans will now look as pure objects as this will also support inheritance and polymorphism.Following is the source code for an entity bean.:
@ENTINTITY PUBLIC CLASS EMPLOYEE {
PRIVATE Long Empno;
PRIVATE STRING Empname;
Private address address;
Private hashmap projects = new hashmap ();
PRIVATE DOUBLE SALY;
@ID (generate = sequence) public long positionEmpno () {
RETURN EMPNO;
}
Protected void setempno (long Empno) {
THIS.EMPNO = Empno;
}
Public string geTempname () {
Return Empname;
}
Public void setempname (String Empname) {
this.empname = Empname;
}
@Dependent public address getaddress () {
Return Address;
}
Public void setaddress (address address) {
THIS.ADDRESS = Address;
}
Public set getProjects () {
Return Projects;
}
Public void setProjects (set projects) {
THIS.PROJECTS = Projects;
}
Public Double getSalary () {
Return Salary;
}
Public void setsalary (double salary) {
THIS.SALARY = SALARY;
}
....
}
IF you look at the code, you will find what the bean class is a concrete class and not an abstract class the current entity bean.
There are several improvements are being made for the query capabilities in EJB QL and support of SQL queries in the entity beans. A new EntityManager API similar to Hibernate and a simplified version of TopLink 'Session API is being proposed to manipulation of entity beans ie creation , REMOVAL, FINDING OF Entity Beans.
We will Closely Examine The Details of The Proposed CMP Entity Beans in a FOLLOWUP ARTICLE.
Simplifying Client View for EJBS
Using EJBs ie to lookup and invoke is very complex even if EJB is collocated in the application. J2EE 1.4 and EJB 3.0 spec is working on to simplify the client's view of EJBs.If you want to use an EJB presently you have to define the ejb -ref or ejb-local-ref in the deployment descriptor, lookup the EJB and then invoke. If we want to invoke our HelloWorld EJB, following is the simplest way you can invoke an EJB with the current implementation.
First Define The EJB REFERENCES in The Deployment Descriptor as Follows:
EJB-REF>
. T....................
Try
{
Context context = new initialContext ();
HelloWorldHome HelloHome =
(HelloWorld) PortableRemoteObject.narrow (Context.lookup
("Java: Comp / Env / EJB / HelloWorldejb"), HelloWorldHome.Class;
HelloWorld Hello = HelloHome.create ();
....
}
Catch (RemoteException E)
{
System.err.println ("System / Communication Error:" E.GetMessage ());
}
Catch (Namingexception E)
{
System.err.println ("Communication Error:" E.getMessage ());
}
CATCH (CREATEXCEPTION E)
{
System.err.Println ("Error Creating EJB Instance:" E.GetMessage ());
}
AS An Alternative to Environment Variables, EJB 3.0 Proposes A Way To Use Setter InjBS.
FOLLOWING IS WAY OUR HelloWorldejb Can Be Looked Up Another EJB BY Using Setter Injection.
@Inject Private Void SetSessionContext (sessionContext CTX) {
this.ctx = CTX
}
...
MyHello = (HelloWorld) CTX.lookup ("Java: Comp / ENV / EJB / HelloWorldejb");
If you look at the code above carefully the setSessionContext method is annotated with @Inject to specify that dependency injection be used for this method. The injected methods will be invoked by the container to set the EJBContext before any business method be called on that EJB.
Another Direct Example To Inject The HelloWorld Session Bean Would Be To Simply Have @EJB Public HelloWorld Myhello and this Would Cause MyHello To BE INJECTED WITH ANSTANCE OF TO BEELLOWORLD BEAN.
YOU CAN Use Dependency Injection To Lookup Any Type of Environment And Resource References Such As Datasource, JMS, Mail, Web Service, etc.
Testability USAbility Outside Container
A major concern for the current EJB developers is not only development of EJBs is complex but also testing is a nightmare. An EJB container is required is to develop and test the EJBs and the developers have to be familiar with the final deployment platform to perform testing . This may not be a major issue for many enterprise developers but is an issue for ISVs who work on supporting multiple vendors and they have to maintain multiple environments to do the testing of their EJBs. The EJB 3.0 spec promises to provide the ability to test Outside the container but this is currently missing in the draft specification.
Conclusion
Although there are a lot of missing information about packaging, assembly and gory details of APIs, the proposals made in EJB 3.0 drafts looks very promising for enterprise java developers. These will certainly help remove the complexities from developers view by passing those to the container vendors IT IS To Be Seeen How The Container Vendors Implement There and Make EJB 3.0 A Compelling Option To Develop Enterprise Applications.references and Further Reading
EJB 3.0 Draft Specification
Author bi
Debu Panda is a principal product manager of Oracle Application Server development team, where he focuses his efforts on the EJB container and Transaction Manager. He has more than 13 years of experience in the IT industry and has published articles in several magazines and has presented at .