Simplifying EJB Development with EJB3.0

Source: Internet
Author: User
Tags getmessage
Enterprise JavaBeans (EJB) is introduced to build distributed components. Initially, the technology promises to solve all of CORBA's problems and reduce its complexity. As the core of Java EE, EJB has undergone several major revisions and added many features, thus becoming bloated. From the outset, most developers were very fond of ejbs and even used EJBS in their applications without any sense of meaning. Many developers blame EJBS when the project does not expand properly and when EJB is used.

EJB development has never been easier, on the contrary, it has become more and more complex as the EJB specification has been released successively. Because of its complexity and its huge system, EJB is likened to an elephant. Many developers think of EJB as a layer of sugar outside of a doughnut-cake. In an era of fanatical diet and low carb, the EJB Expert Committee had no choice but to try to provide "Low-sugar" EJBS to simplify the development of EJBS. The EJB 3.0 Expert Committee released the first public draft of the EJB 3.0 specification during the JavaOne 2004 session and presented a sample picture of a lightweight model.

The new EJB module gives the first impression that it looks beautiful, and in this article, we'll discuss how EJB 3.0 wraps itself in a more dapper way, attracting developers ' attention. In another article that follows, we'll discuss how EJB3.0 simplifies the persistence model.

complexity of the EJB model

Before we start talking about the new features that EJB 3.0 brings, let's look at the complexities of the current EJB model. The current EJB model needs to create several component interfaces and implement several unnecessary callback methods. These component interfaces need to implement EJB Object or EJB localobject and need to deal with a number of unnecessary exceptions. The EJB deployment descriptor is complex and error-prone. The persistence of container management is based on the EJB model and is also very complex, which is not conducive to development and management. Lack of basic functionality, such as defining primary keys by using database sequences in a standard way, and EJBQL is very restrictive. EJB components are not the same as their source objects because of constraints on inheritance and polymorphism. One of the main drawbacks of EJB is that it is not possible to test the EJB module outside of the EJB container, and it is a terrible thing for developers to debug EJBS inside the container. If you have used EJBs, you will know how complex it is to find and invoke EJBs. In order to use EJBS in your application, you must understand every detail of JNDI.

Simplify developer View

If you develop EJBS with the latest specifications, you will find it difficult to develop a simple ejb like HELLOWORLDEJB. You need at least two interfaces, a bean class, and a deployment descriptor. Most developers are thinking: what am I going to do with this? Developers can easily accomplish these chores in the Ides of Oracle JDeveloper, Eclipse, and XDoclet, but developers are still responsible for compiling these classes and wrapping deployment descriptors before deploying the EJB to the selected container.

EJB 3.0 wants to overcome this complexity by using the interface and the deployment descriptor instead of using the metadata annotation for the container to build. Use common Java classes as EJBS, using common business interfaces for EJBS.

Meta Data Annotations

EJB 3.0 is highly dependent on metadata tokens. Metadata tokens are normalized under JSR 175 and will be included in J2SE 5.0. Annotations are a property-oriented programming, similar to Xdoclet. However, unlike the XDoclet that need to be precompiled, annotations are compiled at compile time by the Java compiler into the class (depending on how the @Retention is set). For developers, annotations are similar to public modifiers that can be used in classes, fields, methods, parameters, local variables, constructors, enumerations, and packages. You can use annotations in Java code by specifying properties that can be used to generate code, archive code, or provide special services (enhanced business-level security or specific business logic) at run time. The goal of the Java EE 1.5 (5.0) is to use annotations to simplify development, so it provides its own 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 to use Meta data annotations to generate several artifacts similar to interfaces, using annotations instead of deployment descriptors.

using POJO and Poji

In canonical terms, JavaBeans and interfaces are often referred to as Plain old Java Objects (POJO) and Plain old Java Interfaces (Poji). Today's EJB classes and interfaces will be similar to Pojo and Poji respectively. Unnecessary artifacts, such as the home interface, will no longer be required.

Developers must either be in javax. Implement an EJB interface (Sessionbean, Entitybean, or Messagedrivenbean) in Ejbpackage, or use annotations in the Bean implementation class. You can use stateless, Stateful, Messagedriven, or Entity to annotate the Bean class. For example, if you define a stateless EJB as HelloWorld, you can define the EJB as follows:

@Remote
  @Stateless public class Helloworldbean {public
 string SayHello (string s)
  {System.out.println (" Hello: "+s;}
  }" 

EJB interfaces can be either remote or local, and do not have to implement Ejbobject or Ejblocalobject. You must provide the business interface for the EJB and implement the interface in the Bean class, or build the interface during deployment. Interfaces are optional for entity beans, but interfaces are required for Sessionbean and Messagedrivendriven. If no interface is implemented for the session bean, a bean interface is generated. The generated interface type can be local or remote, depending on the annotations used in the Bean class. It is clear from the code example above that @Remote is used to generate a remote interface for the HelloWorld bean. If you want, you can provide both a remote interface and a local interface for the EJB.

The above example clearly shows that there is no need for developers to perform a large number of common tasks, such as defining interfaces and implementing callback methods.

The name of the generated interface originates from the name of the Bean implementation class. The generated interfaces are really good for developers. However, I don't think generating interfaces has much of an advantage because most Ides, such as Oracle JDeveloper, can dynamically build these interfaces.

The draft does not clearly explain what client requirements for EJB lookups are, and how to get the interfaces needed to invoke that EJB. I recommend that you do not use the generated interface for the following reasons: The name of the generated interface will derive from the bean name you may not want to advertise some methods in the EJB in the generated interface, and by default, the generated interfaces will expose all the methods. You need the client interface to invoke the EJB.

callback method is no longer needed

EJB2.1 and previous versions require that several lifecycle methods be implemented for each EJB, such as Ejbpassivate, Ejbactivate, Ejbload, Ejbstore, and so on, even if these methods are not required. For example, the stateless session bean does not need to be ejbpassivate, but it still needs to be implemented in the Bean class. Since the current EJB3.0 is similar to a normal Java class, implementing these lifecycle methods is not necessary. If the callback method is implemented in the EJB, the container invokes the method.

The only exception is the EJB remove method in the Stateful session bean, where the remove callout can be used to annotate the Stateful session bean business method in the Stateful session Bean. If this callout is used, it will prompt the container to delete the Stateful session Bean instance after the annotated method completes (normal or abnormal completion). For example, you can specify that the following code deletes an Stateful session bean instance after the CheckOut method has been executed.

@Stateful public class Cart {
...
...
@Remove public void CheckOut () {
...}}
}

Callout VS Deployment Descriptor

As mentioned earlier, the EJB will no longer need a deployment descriptor and will use annotations. The default values for each property in the deployment descriptor are selected, and developers do not need to specify these properties unless you want to use a value other than the default value. You can specify these values in the Bean class itself by using annotations. The EJB 3.0 specification defines a set of metadata annotations for a developer, such as bean type, interface type, resource reference, transaction attributes, security, and so on. For example, suppose we want to make a resource reference to a particular EJB, define the following:

@Resource (name= "Jdbc/oracleds", resourcetype= "Javax.sql.DataSource")

Java EE vendors, such as Oracle, BEA, and IBM, will add attribute annotations to their vendor-specific deployment descriptors, which developers will use to avoid deployment descriptors. This is quite attractive for developers, because there is no XML descriptor that they hate most. However, this also poses some problems, and we need to be more cautious before using the tag. This prevents the application portability target from being implemented because if the EJB uses a vendor-specific deployment descriptor and does not recompile/repackage the EJB, the change will not be fulfilled. Without having to view the EJB one by one, the deployment descriptor provides a complete view of the EJB module for the assembler/Deployer (Ejb-jar), which also adjusts these views as per the requirements for each deployment. If the descriptor is not available or is not generated until the end of deployment, the consequences can be disastrous. Various tools use the deployment descriptor to identify EJBS in the EJB module, which is useful when migrating between containers.
The EJB 3.0 specification also proposes a way to override annotations in the deployment descriptor. However, the specification does not give specific details of the rewrite tag.

There is no doubt that no longer using the deployment descriptor will make it easier for new developers to work, but if used improperly, management issues may arise.

simplifies container-managed persistence

EJB 3.0 has revolutionized the CMP entity bean to attract the attention of developers. Persistence frameworks (such as Oracleas toplink), open source Hibernate, have become the darlings of the development of the Java EE Application Persistence framework, and entity beans are no longer popular because they are both complex and heavy. EJB 3.0 employs a lightweight persistence model similar to TopLink and Hibernate to simplify container management persistence, which is certainly tempting for developers. Let's take a quick look at the entity Bean Plan, the details of the persistence improvements, which we'll discuss in another article.

Entity beans are being reborn as POJO, and entity beans will no longer need component interfaces. Now the entity Bean will be treated as a pure object, because it will also support inheritance and polymorphism.

The following is the source code for the entity bean:

@Entity public class employee{
  private Long empNo;
  Private String EmpName;
  private address address;
  Private HASHMAP projects = new Hashmap ();
  Private Double salary;
  @Id (generate=sequence) public Long getempno () {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) {
  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;
  }
  ....
  }

Looking at the above code, you can see that this bean class is an entity class for the current entity bean, not an abstract class.

There are several improvements to query functionality in the EJB QL, and SQL queries are supported in entity beans. A new Entitymanager API similar to Hibernate (a simplified version of the TopLink ' session API) is used to manipulate entity beans-creating, deleting, and locating entity beans ...

We will examine the details of the proposed CMP entity Bean in the next article.

Simplified client view of EJB

The use of EJBS (that is, lookups and invocations) is complex, even though EJBS have been configured in the application. The Java EE 1.4 and EJB 3.0 specifications are precisely the client views that are to simplify the EJB.

If you want to use EJBS now, you must define EJB-REF or EJB-LOCAL-REF in the deployment descriptor, look for EJBS, and then call again. To invoke the HelloWorld EJB, the following is the simplest way to invoke the EJB in the current implementation.

First, you define the EJB reference in the deployment descriptor, as follows:

<ejb-ref>
  <ejb-ref-name>HelloWorldEJB</ejb-ref-name>
  <ejb-ref-type>Session< /ejb-ref-type>
  
Then, use the following code to find the EJB. You must explicitly handle the EJB lookup and create exception conditions for the Bean instance.
Try
  {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 (createexception e)
	{
	  System.err.println ("Error creating EJB instance:" + e.getmessage ());
	}

For environment variables, EJB 3.0 suggests an alternative approach, using setter injection to find and invoke EJBs.

The following code is a method of using setter injection to find HELLOWORLDEJB in another EJB.

@Inject private void Setsessioncontext (Sessioncontext ctx)
  {
  this.ctx = ctx
  }
  ...
  MyHello = (HelloWorld) ctx.lookup ("JAVA:COMP/ENV/EJB/HELLOWORLDEJB"); 

With a careful look at the code above, you can see that the Setsessioncontext method is annotated with a @Inject to use dependency injection for the method. The injected method is called by the container to set Ejbcontext before invoking any of the business methods on the EJB.

Another direct example of injecting a HelloWorld session bean is to use only the @EJBpublic HelloWorld MyHello, which causes MyHello to be injected through a HelloWorld bean instance.

You can use dependency injection to find any type of environment and resource reference, such as DataSource, JMS, Mail, Web services, and so on.

Testability and availability outside the container

One of the major concerns of current EJB developers is not only the complexity of EJB development, but also the challenge of testing it. To develop and test ejbs without EJB containers, developers must be familiar with the final deployment platform before they can test. This may not be a major problem for many enterprise developers. But for ISVs that support multiple vendors, this is a real problem, and they have to maintain multiple environments to test their ejbs. The EJB 3.0 specification promises to provide the ability to test outside the container, but the details are not currently mentioned in the draft specification.

Concluding remarks

Despite the omission of a lot of packaging, assembly, and API details, the proposal in the EJB 3.0 draft is still tempting for enterprise Java developers. Leaving this work to container vendors will help reduce the complexity of the problems that developers face. This depends on how the container vendor implements the work and makes EJB 3.0 an inevitable choice for developing enterprise applications.   

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.