Persistence Problems

April 30, 2008 at 12:52 pm (EJB, Extra) ()

By Geir Magnusson Jr. and Jeremy Boynes

June 9, 2004

By Geir Magnusson and Jeremy Boynes

We seem to have a big problem in the Java persistence community, and it’s one that seems to have a surprisingly simple solution.

Storm clouds

About mid-May 2004, we began to suspect that things weren’t quite right, about the time the SE/EE Executive Committee voted on JSR-243 for JDO 2.0. Several EC members voted against the JSR, although it did pass. You can read about it here. [Full Disclosure from Geir : I'm the Apache EC rep and voted yes because I think that despite assertions to the contrary, there is no overlap with existing technology, and if there *is* overlap, competition is good - let the market decide.] Looking back, there was a hint of storm clouds on the horizon with Oracle’s comment, namely that JDO 2.0 overlaps work being done in the EJB expert group. We didn’t think anything of it at the time (“JDBC overlaps work being done in the JNDI expert group” if you believe that both are ways of retrieving data) but with the benefit of hindsight, it’s almost as if Oracle was warning us about what was coming.

Looking back at the comments, we also have several references to J2EE. JDO isn’t part of the J2EE spec – JSR-243 notes it will work to be more “aligned” with J2EE – and J2EE isn’t the only platform under which people build applications. JDO is important for non-J2EE developers working on J2SE applications. With further hindsight, we see from those comments that several platform vendors appear to have identified a developer need unfilled in the J2EE platform.

The Three Tiers of the Persistence Inquisition

We tend to think about persistence tools in the way we think about any other set of developer tools for a given technology. Generally, once software engineers have enough experience in a problem domain, they will produce a set of development techniques or models which are designed to address different levels of complexity in that problem domain. They tend to build on one another and if lucky, there’s a reasonable path for moving ‘up the chain’ as an application’s complexity increases. This model and tool approach is true with persistence as well:

  1. Simple and Uncomplicated: At the bottom of the complexity stack of Java data persistence is the old ‘fast and dirty’ standby that we all know and don’t truly love – JDBC. We’ve all used it and gotten quite a bit done with it, but it’s not terribly pleasant when we live in an object-oriented world (or even a data-structure world). We tend to write simple tools to help us around the “bare metal”, and after a while, we stand back, look at those simple tools, and and decide that we need a better level of abstraction to handle the domain model that we work in. That leads to tools and models of medium complexity.
  2. Medium complexity: This consists of tools that allow us to work easier with the everyday objects and data structures that make up our applications. This isn’t a new idea, and probably extends from seeing object database systems and, not being able to actually find any in the market ;) , wanting to use general purpose RDBM systems for the same purpose. There is a wide range of approaches to this problem, from populating JavaBeans from XML (and back) to POJO persistence, with solutions ranging from standard to proprietary, commercial to open-source. Examples include the Java JDO specification with it’s implementations, commercial proprietary O/R systems like TopLink and the current crop of open-source solutions like Hibernate, OJB, Cheyanne, et al. The basic idea in middle-complexity-land is fundamentally about persisting POJOs (Plain Old Java Objects). These approaches generally are very convenient to use, allow you to work without any component contracts forced on your classes by the environment, and more or less give you the freedom to easily save objects or graphs of objects to some kind of data store and get them back later. They tend to be “deliberate” – the programmer makes the decision about when to save with some kind of explicit POJOFramework.save(myObject) call or -ish. They also are very popular (and becoming increasingly so) because most applications seem to be at this level of complexity – you just want to work with your domain objects in a deliberate way. (Or even just use to ‘persisted data structures’, which is my favorite use for Hibernate, for example).
  3. High Complexity: To address high levels of complexity, we have complicated frameworks like EJB that provide middleware services such as transactions, security, data storage, component relationship management, etc. This third tier is generally very powerful, very complicated, and seems to be often misapplied. Because it’s part of the ‘enterprise’ Java standard, it’s the ‘natural’ choice for persisting data in an ‘enterprise’ application, although there are other solutions that, depending on the application, would be just as appropriate and easier for the developer to use, deploy and maintain – solutions from medium-complexity-land that aren’t part of the J2EE spec.

J2EE, EJB and Thee

With the preceding discussion in mind, lets look at what’s been happening with the next version of J2EE. According to the text of JSR-244, the theme of J2EE 1.5 is “ease of development”, with the goal of addressing the needs of a wide range of developers, “including less sophisticated developers”. This is a laudable goal, and quite frankly, it’s about time. By adding new features that enable better tool support, ease of application development, and ease of maintenance, the Java will hopefully become more widely adopted and remain a competitive platform for enterprise development.

Expert groups that are part of the J2EE “umbrella” are working to support that goal, and this includes Enterprise Java Beans (EJB). The JSR for EJB 3, JSR-220, has the following as its declared purpose :

“The Enterprise JavaBeans architecture is a component architecture for the development and deployment of component-based business applications. The purpose of Enterprise JavaBeans (EJB) 3.0 is to improve the EJB architecture by reducing its complexity from the developer’s point of view.”

It makes it pretty clear that EJB is a component architecture (and happens to include the ‘high complexity tier’ of data persistence) and the intent of this version is to improve the architecture by reducing complexity. This is just fabulous.

POJO Persistence and Mission Creep

As we’ve heard at TheServerSide Symposium and other places, the EJB expert group is working on what amounts to splitting the EJB spec into two concurrent ‘tracks’. They don’t talk about it like this, but it’s a reasonable interpretation :

  • an addition of a new and incompatible POJO persistence model
  • a continuation of the EJB 2 component architecture with new POJO persistence model features backported (changes to query language, for instance)

We think that one conclusion that we can safely draw from this is that the EJB3 expert group recognizes that EJB2 persistence doesn’t satisfy the needs of a large number, if not the majority, of enterprise application developers. Further, they recognize that POJO persistence is a valid persistence strategy and developers like to use it for their applications. They are so interested in having it available, the EJB expert group is willing to alter the objective of the JSR to accommodate.

I think that we should appreciate the EJB3 EG for the courageous step of effectively saying “We realize there’s more to enterprise data persistence than EJBs and we want to do something about it” It’s not unreasonable, though, to presume that this ‘bifurcation’ of the EJB spec will be fairly confusing for developers because now EJBs are going to be “EJBv2 EJBs” and “persisted POJO EJBs”.

Paying attention to customer demand is laudable, but when you consider that these two technologies (POJO persistence and EJBs) are arguably two distinct solutions to data persistence appropriate for differing levels of application complexity (and EJB is more than just data persistence), this bifurcation of the spec begs a question :

“Could we prevent an over-broad and potentially confusing EJB model by simply adding POJO persistence separately to the J2EE spec for 1.5?”

One would assume, given the investment made by users and vendors of J2EE, that an incremental revision of the J2EE spec (from 1.4 to 1.5) would presume a compatibility path that preserves existing investment and allows those implementations to smoothly take advantage of new features. Users aren’t going to want to rewrite critical business applications just to keep up with vendors. What we seem to be seeing here is a discontinuous change from EJB2 to EJB3 and there is no smooth path from EJB2 applications to EJB3 applications.

To answer the question above, we could achieve the same result by making a POJO persistence model available in J2EE distinct from EJB without compromising EJBs, which are a valuable and appropriate solution for a small percentage of highly-complex enterprise applications. Not everyone needs EJB, but when you do, you do!

The obvious solution – “Well, you’ve had a JSR for POJO persistence for some years now… JDO – why not add it to J2EE?” – is an answer that no one seems to want to hear because there appears to be a war going on between the JDO and EJB communities. Technology battles aren’t new, but this one is astounding in it’s irony. The EJB3 group, by adding POJO persistence, is validating the whole argument for JDO or a JDO-like technology in J2EE. There will be arguments about technical details such as choice of query language, approaches to detaching object graphs, etc but at the end of the day, the EJB EG is advocating the addition of a technology approach that already exists in the “Java ecosystem” – JDO – into J2EE.

We’re optimistic that this can be resolved. We don’t believe that a spec lead can be held responsible for the public behavior of the expert group members or non-EG members of the community. However, as both specs are Sun sponsored, both spec leads are Sun employees and most importantly, all parties agree on the fundamental need for POJO persistence in J2EE, it’s conceivable that through a concerted effort by Sun to recognize the gap in J2EE and work towards an architecturally clean solution, partisans from both sides can work with each other rather than against each other.

Solution!

The simplest solution is to add POJO persistence (via JDO 2.0 or other) to the J2EE umbrella. As a bonus, require that POJO persistence and EJB work from the same persistence layer, so that concurrently deployed applications written using both technologies have coherent views of the same data. (And if vendors are smart, they’ll provide a JDBC driver to access the same persistence layer….)

While fixing J2EE to support what programmers want today, it also offers a compelling path to J2EE from J2SE, because J2SE applications that are written using the same POJO persistence model will be able to migrate to the J2EE environment without requiring changes to their persistence model. Further, we can take a lesson from Microsoft’s ADO and tools such as Hibernate and OJB in Java – that there is a strong demand for persistent objects in the base platform. So lets also ensure that we take what we learn from J2EE 1.5 and push what we can ‘down’ to J2SE 1.6. (On that note, how many people know about the rejected JSR-20?)

JDO 2.0 just got started. Any of the supposed deficiencies in JDO can be addressed. If, in the opinion of the J2EE EG, that JDO’s model is inappropriate – that recent work in open-source or commercial solutions offer compelling alternatives – start a new EG and include members from JDO as well as EJB.

We feel that this is an important problem, but a very manageable one, and hope that the broad Java community supports this approach – addressing the needs of the development community is one of the core purposes of the JCP. Lets use it.

Note: The above represents the personal opinion of Geir and Jeremy and should be not construed to represent the position of any other organization. Specifically, this does not represent the position of the Apache Software Foundation.

Full Disclosure: Geir is the Apache representative to the JCP Executive Committee and recently the current Apache representative on the J2EE 1.5 Expert Group. Jeremy is the Apache representative on the EJB3 expert group. This article is an original work by Geir and Jeremy based on public information and should not be construed to represent either EC or EG confidential information, future intention or past or current discussion. If any of this has been discussed in an EG, it is without our knowledge and we consider ourselves lucky.

Permalink Leave a Comment

Simplifying EJB Development with EJB 3.0

April 30, 2008 at 12:49 pm (EJB, Extra) ()

By Debu Panda


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 announced 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 complexities in the current EJB model before we dive down 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 cannot 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 EJBs

Metadata 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 that @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 generating interfaces as most IDE like Oracle JDeveloper generates these on fly.

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 cannot 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 not used carefully.

Simplifying Container Managed Persistence

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:

@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 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 that 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 i.e. 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 i.e. 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>

<ejb-ref-name>HelloWorldEJB</ejb-ref-name>

<ejb-ref-type>Session</ejb-ref-type>

<home>hello.HelloWorldHome</home>

<remote> hello.HelloWorld</remote>

</ejb-ref>

Then lookup the EJB as follows. You have to explicitly handle exceptions for EJB lookup and creation of a bean instance.

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(CreateException 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 injection to lookup and invoke EJBs.

Following is way our HelloWorldEJB can be looked up in 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 an instance of the HelloWorld 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 seen how the container vendors implement these and make EJB 3.0 a compelling option to develop enterprise applications.

References and further reading

Permalink Leave a Comment

Inheritance & EJBs

April 30, 2008 at 12:45 pm (EJB, Extra) ()

By Daniel O’Connor


June 2002

Discuss this Article

Introduction

One of the most common criticisms of entity EJBs is that they don’t support inheritance or polymorphism. If this were true, it would be a serious complaint for two reasons. First, entity beans are intended to provide an object-oriented view of information in a persistent store, and inheritance and polymorphism are key aspects of the object-oriented programming paradigm. Second, many bean developers are using relational database schemas that essentially implement a form of inheritance, and they need to be able to operate on these schemas with their EJBs. However, in practice, entity EJBs are capable of meeting these requirements.

In this article I’m going to show how to implement entity bean inheritance with three CMP EJBs: a “base class” PARTY EJB and two “derived class” EJBs: PERSON and CORPORATION. (This is a common design in relational database schemas.) Furthermore, I’ll demonstrate a polymorphic finder query and a couple of polymorphic method calls. The beans I produce will be absolutely portable according to the EJB 2.0 specification.

I’ll also show how these container-managed persistence beans can be mapped to a standard relational database schema for this type of data. The EJB specification does not require particular object/relational mapping capabilities from an EJB container’s CMP engine. It does not even require that the container be able to use relational databases at all, so the ability to map to a particular schema is not portable. However, I am the author of a pluggable CMP engine that provides this capability (the MVCSoft Persistence Manager). We’ll look at how this engine is able to make the sometimes-difficult translation from EJB objects and relationships to database tables, and what is involved from the user’s point of view in using this particular mapping.

Some Distinctions

It’s important to be clear exactly what we mean when we talk about inheritance. In this case there are three possibilities, and this article is mostly about a single one of these possibilities. First, there is the language inheritance with which every competent Java programmer is familiar. The Java language allows a class to extend a single immediate base class, which can in its turn extend another single base class, until the universal base class of java.lang.Object is reached. It also allows an interface to extend one or more interfaces. Finally, it allows a class to implement any number of interfaces. The EJB specification allows for any of the interfaces or implementation classes associated with a bean (remote home and component interfaces, local home and component interfaces, primary key class, and bean implementation class) to take advantage of these Java language features. (There are a few caveats, such as requirements for the return types from create methods.)

Second, there is an amorphous concept called “component inheritance.” Although frequently used (even once in the EJB spec itself), there is no generally accepted definition of the term in this context. It would probably include (1) the ability to extend an existing entity without modifying the base component or even having the source code; (2) the ability to compare component interfaces of different types for equality; and (3) the ability to return different component interfaces from a single finder or ejbSelect method.

Third, there is “data model inheritance.” This is the ability to model an inheritance hierarchy of business objects (and their polymorphic behavior) using entity EJBs. It is this last type of inheritance that this article addresses. Note that whereas language inheritance and component inheritance might be considered “implementation details,” data model inheritance directly affects what can and cannot be accomplished using EJBs.

Why the Criticism?

If entity EJBs are capable of inheritance and polymorphism, why do people frequently say they are not? One source for this criticism can be found right in the EJB 2.0 specification. Section 11.2.11 says, “The data model for container-managed persistence does not currently support inheritance. Therefore, entity objects or value classes of different types cannot be compared. EJB QL queries that contain such comparisons are invalid.” Furthermore, the list of features deferred to future releases includes “support for component-level inheritance.”

In fact, there is no framework support in the EJB spec for inheritance and polymorphism. This has consequences for all three types of inheritance discussed above. It makes component inheritance–by any reasonable definition–impossible. It places limitations on how language inheritance is used. It requires the bean developer to implement data model inheritance on his or her own, while being mindful of the limitations of the EJB component model. This lack of framework support, and the consequences, are the issues that ultimately generate the criticism.

But that’s a far cry from saying that entity EJBs are incapable of representing an inheritance hierarchy, or polymorphic behavior, in a data model. When enterprise software developers hear about the lack of inheritance in EJBs, they most likely assume that EJBs cannot work with their existing schema. But they can, and this is the important point by far. In practice, it’s not that significant that you don’t have “black box” component-level inheritance for EJBs. What’s important is that you can represent your complete existing enterprise schema using EJBs.

How to Do It

It’s not complicated to implement a schema incorporating inheritance. The fundamental technique is called “containment.” This just means that your base EJB component will have a reference to its derived class or classes, and will delegate calls as appropriate. The base class will need some way of determining how to delegate the call to a related “derived” class. Typically, there will be a field (called a discriminator) that establishes the type of the base class. In its simplest form, a business method would check this discriminator, retrieve the appropriate related entity component interface from a cmr field, and delegate the call to this interface. For example, a business method call on a PARTY component interface would be translated by the container to a call on the PARTY implementation class. The PARTY implementation class might check a discriminator CMP field, and depending on the result, delegate the business method call to the PERSON cmr field or the CORPORATION cmr field.

Polymorphic relationships between entities will actually be between base EJB components, and polymorphic EJB-QL queries will return references to the base EJB component. For instance, if there were an ORDER component, it might have a relationship to a PARTY bean, rather than either a PERSON or CORPORATION bean. Or if you called a finder that retrieved all the orders in Ohio, you would query on the PARTY bean rather than the PERSON or CORPORATION bean.

It is possible that there might be methods defined on a subclass component interface that aren’t defined on the base component interface. You can’t use Java language casting to downcast from the base interface to the subclass interface…but you could implement a business method that returned the desired derived component interface. An elegant signature might be EJBLocalObject dynamicCast( String type ).

The example code for this article implements four EJBs: a session bean fafacadeade and the three entity EJBs (PARTY, PERSON, and CORPORATION). A client will ask the session bean facade to create some sample data: three people and three corporations. It will then execute a findAll() query that returns all six of these EJBs in a single result set. It will call two polymorphic business methods, one getting a display name and one getting a credit rating. There is nothing special about any of the code, but I’ll review the parts that are relevant to inheritance or polymorphism.

First, I have provided a business interface from which every local component interface in the inheritance hierarchy derives. (See PartyIntf.java.) This is not a requirement, but it allows us to treat any local component interface in the hierarchy as a single type with polymorhic methods. If I had not done this, the business methods of all three of the component interfaces would still function correctly, but the client would not be able to treat a party component interface, a person component interface, and a corporation component interface as the same type. Really, this is just syntactic sugar.

In this example, the polymorphic behavior is implemented entirely in the PARTY bean implementation class. (See PartyBean.java.) There is a cmp field “typeCode” that indicates the derived type of the entity. There are also two cmr fields to contain the derived instance: corporation and person. In this example, they are mutually exclusive and one of them will be null, but this is not a fundamental requirement. (In other words, you can implement multiple inheritance if your schema requires it.)

There are two business methods: getDisplayName() and getCreditLimitCode(). When either of the business methods is called, the typeCode cmp field is checked and the business method is delegated appropriately. For example:

public String getDisplayName()

{

String code = getTypeCode();

if (code.equals(“I”))

return getPerson().getDisplayName();

else if (code.equals(“C”))

return getCorporation().getDisplayName();

throw new EJBException( “Unknown type” );

}

You could make a case that the typeCode is redundant and it should be possible to check which relationship is not null. But if the cmr field is being lazily loaded by the EJB container, this could result in unnecessary database I/O.

The findAll() query (used by the session bean facade and called by the client) is defined on the PARTY local home interface. Of course, it is only returning component interfaces for the PARTY EJB, but these represent both PERSON instances and CORPORATION instances. It is defined in the deployment descriptor as a query returning PARTY instances, as follows:

<query>

<query-method>

<method-name>findAll</method-name>

<method-params/>

</query-method>

<ejb-ql>select object(pb) from PartyBean pb</ejb-ql>

</query>

The last interesting pieces of code from this example are the ejbCreate and ejbPostCreate methods for the CORPORATION and PERSON beans. As well as creating the corporation or person instance, respectively, these methods need to create the corresponding PARTY instance and establish a one-one relationship between the two. You might wonder if any special technique is required, considering that the relationship between a PARTY instance and a CORPORATION or PERSON instance is likely implied by a migrated key, rather than being explicitly stored in a separate foreign key. But this is a detail of the object/relational mapping, and doesn’t enter into consideration when you are coding your component. Let’s take a look at CorporationBean.java’s ejbCreate method:

public Integer ejbCreate( ViewCorporation view )

throws CreateException

{

getPartyLocalHome().create(new ViewParty(view.getId(), “C”));

setViewCorporation( view );

return null;

}

This is just one possible implementation, but the basic steps will usually be the same. In the ejbCreate method, we create an instance of the PARTY base component, and initialize the cmp fields for this component. Then in the ejbPostCreate method, we establish the relationship between the two:

public void ejbPostCreate( ViewCorporation view )

throws CreateException

{

try

{

PartyLocal party = getPartyLocalHome().findByPrimaryKey(view.getId());

setParty( party );

}

catch (FinderException e)

{

throw new EJBException( “Party not created” );

}

}

Object/Relational Mapping

For most enterprise developers, modeling inheritance and polymorphic behavior in EJBs is just half the battle. The other half is working with an existing schema. The code with this article should work with any EJB container, but there are no requirements in the EJB spec for any set of mapping capabilities. In practice, you’ll find that there is substantial variation in capabilities between implementations, and there are three potential trouble spots here.

First, the most common database schema for this model will have a migrated primary key that establishes the relationship between the base and derived entities. In the EJB world, primary keys and relationships are completely unrelated. The persistence mechanism for your EJB container must be smart enough to realize that in this case, the primary key and relationship information in the persistent store are conflated.

Second, the typical database schema for this model will have foreign-key constraints on the migrated primary key. This requires that the database inserts take place in the correct order (to not violate these constraints). If the EJB container triggers the insert statements immediately on return from ejbCreate, you must make sure that your code is ordered correctly. The persistence manager I wrote (the MVCSoft Persistence Manager) can cache the data and write it out to the database at the end of the transaction, dynamically reordering the database i/o so as to not violate any constraints.

Finally, if your EJB container is lazily-loading relationships for large result sets, it can lead to unacceptable performance. In our example, each call from the PARTY bean to getCorporation() or getPerson() might result in a select query to the database to get the information. There are several possible solutions to this problem. For example, the MVCSoft Persistence Manager allows you to define a “fault group” for a query that defines the information you will need during the transaction, and this fault group can extend to related information. The runtime will eagerly load the required data using a minimum number of queries. If you issued a finder query that returned a hundred results and called a polymorphic method on each instance, a properly configured runtime will issue three queries, rather than 101 queries as in the lazy loading case.

Conclusion

Despite what you may have heard, entity EJBs can be used effectively to represent business objects with inheritance and polymorphic behavior. There is no support for this functionality in the EJB component model, but one simple technique–called containment–is to delegate polymorphic business method calls to appropriate “derived” component instances. The EJB specification does not mandate specific object/relational mapping functionality, but there are products that can work with your existing relational database schema.

Permalink Leave a Comment

Deciding whether EJB is appropriate

April 30, 2008 at 12:41 pm (EJB, Extra) ()

By Ed Roman

excerpted from the new “Mastering Enterprise JavaBeans 2nd edition” book
September 2001

Discuss Article here.

Motivation

A recent Gartner Group report cited companies overspent $1 billion on EJB last year, when they could have just gotten by with Servlets/JSPs. This motivates our next discussion: once you’ve decided whether server-side Java is the way to go, you then need to make the all-important decision: are you actually going to use EJB on this project? Or is EJB overkill?

Example

As a motivational example, consider an E-commerce site that has involved business processes. When you buy something on an E-Commerce site, the site needs to:

  • Validate your credit card
  • Debit your credit card
  • Perhaps run some anti-fraud checking algorithms
  • Check inventory
  • Send a confirmation email
  • Submit the order
  • Fulfill the order
  • Track the order afterwards
  • Handle returns

You can still achieve all of this by using vanilla Servlets and JSPs. For example, you could have the Servlets and JSPs call Java classes. Those Java classes perform your business logic. In fact, there are three scenarios that we can consider when it’s possible to use Java classes rather than EJB components:

In a browser client web-based system with Servlets and JSPs, you could use Java classes rather than EJB components.

In a web services system where business partners call your Servlets and JSPs using XML/HTTP, you can also use Java classes rather than EJB components (see for a whitepaper on how to build web services using J2EE).

In a 2-tier client/server system such as a Java applet or Java application connecting to a server, you could again use Servlets and JSPs on the server. The thick client could communicate with the server via HTTP, which easily navigates through firewalls (compared to IIOP, which doesn’t). Behind the Servlets and JSPs could be Java classes instead of EJB components.

NOTE: A Servlet/JSP HTTP layer is only important if the users of your system are going to be behind firewalls, such as anonymous Internet clients, business partners, or other departments within your organization. It’s also important if your thick client is located across the Internet, because HTTP is a lightweight protocol that travels across the Internet easily. If there is no firewall issue, or if your users are not located across the Internet (but rather are on your local area network) you could get rid of your HTTP layer and connect the client to EJB components directly. In this case, the EJB value proposition is very strong, because EJB allows the client to call the server using intuitive method names, removes the need to perform XML marshaling, and gives you automatic remotability and load-balancing.

The Fear, Uncertainty, and Doubt

So how do you decide which is the right paradigm? Let’s start out with the reasons that most people think are important for deciding between EJB and Java classes, but are actually not important at all.

EJB server cost. The major J2EE server vendors, such as IBM, BEA, and Oracle, do not sell their EJB layer separately from their Servlet/JSP layer. They sell a single “J2EE server” which bundles both layers. So if you go with a market leader, then you’re probably going to buy an EJB server whether you like it or not. The only way to avoid this cost is to purchase an open-source or inexpensive Servlet/JSP implementation. This is a viable option, this is not recommended for major deployments. Why? Because the cost of the J2EE server is often a drop in the bucket compared to the total cost of the project. If the server doesn’t work out, consider all the retraining you’ll need to pay for, and the code you may need to rewrite if the servers use different versions of the J2EE specifications. Consider the difficulty in hiring skilled professionals if you don’t go with a market leader, the cost of re-learning how to tune your new server, and the cost of learning how to administer that new server. The cost of the application server should not be an issue for most serious deployments–most major vendors are charging very reasonable fees, far less than the $50,000 per processor that was charged back in the day. Rather, you should consider whether an EJB layer or a Java class layer is appropriate for your project. The professional services fees–we call it geek time–tends to dwarf the application server cost.

Resource pooling. Some people think that only EJB can give you resource pooling. Not true. Almost all the major J2EE server vendors allow you to get connection pooling and thread pooling whether you use Servlets/JSPs or EJB components.

Clean separation of business logic and presentation logic. EJB is nice because it enforces a separation of presentation logic (Servlets and JSPs) from business logic (EJB components). We like this because in the future we can support different types of presentation logic, such as a WAP enabled phone, or an XML data stream client from a business partner. But you can achieve the same results with Java classes instead of EJB components as well. You just need to enforce some coding best-practices in your organization about the proper usage of Java classes as a business layer facade.

Deciding the right way

Now that we’ve blown away the FUD (Fear, Uncertainty, and Doubt), here are the real reasons to use EJB over Java classes:

Your system is built faster and more reliably. EJB components benefit from declarative middleware, such as instance pooling, transactions, security, container-managed persistence, container-managed relationships, and data caching. If you used regular Java classes, you’d need to write this middleware yourself over time. Eventually you might find that you have your own middleware framework. That ‘framework’ is a fancy word for building your own home-grown application server. The framework needs to be tested, debugged, features need to be added. This is a non-trivial task indeed. Can you honestly state that your staff is capable of building a better application server than the market leaders who specialize in middleware?

It is easier to hire new employees. If you build your own custom framework using Java classes, then newhires need to be trained on this framework. If your framework is complex, then you can no longer look for “EJB” on a resume when hiring a developer and expect them to be productive on your system.

You benefit from the best practices the world is building around EJB. You can figure out how to optimize your system by reading articles on the Internet, or picking up a book on EJB best practices, such as Floyd Marinescu’s “EJB Design Patterns” book. This global knowledge base is not at your disposal with a proprietary Java class framework.

You can have different user interfaces. You can reuse the same EJB component layer for a thick client as well as a Servlet/JSP client. With Java classes, you cannot achieve this because Java classes are not remotely accessible. If you wrapped those Java classes in RMI objects, you’d need to invent your own load-balancing, instance pooling, and fail-over.

You can work with industry-standard tools to rapidly develop your system. While in the short run you may think that Java classes are going to make it faster to develop than writing all those files that comprise an EJB component, in reality there are many tools around that help streamline the EJB development process. There are command-line tools that generate the files you need, there are IDEs that help you build EJB components, and there are UML editors that help you generate EJB components from UML diagrams. See for more.

You can separate your web tier and application server. If you require your business logic to be protected by a firewall, then you can deploy the web server and application server on separate machines and stick a firewall in the middle.

And here are the real reasons not to use EJB:

You can’t deal with the limitations of EJB. Examples include threading, static variables, and native code. Most companies can deal with this, because there are good reasons why the restrictions exist. But if (for example) you need to have a multi-threaded engine, and you can’t deal with the EJB paradigm of load-balancing across single-threaded instances, then EJB is not a good fit for you. EJB is a square peg–don’t try to stick it into a round hole.

Your have existing skillsets or investments in a working technology. For example, if your developers are proficient in CORBA, then great–why not stick with it? As an anecdote, The Middleware Company consulted with one of our clients who wrote a CORBA application that assisted with mapping the human genome. It worked well with CORBA, and they had no major complaints, and so we recommended they stick with CORBA and avoid the EJB hype.

Your application is a big GUI to a database. If you are just a big GUI to a database–heavy on data logic but no business logic–you could achieve a deployment easily using JSPs with tag libraries connecting to a database via JDBC.

Your application is simple. If you are prototyping, building a simple system, or developing a one-off application that will not evolve over time, EJB may be overkill.

Permalink Leave a Comment

J2EE Vs .NET

April 8, 2008 at 3:15 pm (.NET, Extra) (, )

Click the link

j2ee-versus-net

Permalink Leave a Comment

The Component Object Model (COM)

March 8, 2008 at 3:41 pm (COM, Extra) ()

When Microsoft designed OLE, it had object-oriented programming in mind. COM objects are much like instantiated C++ classes or an ADA package. In fact, COM was designed with C++ programmers in mind. It supports encapsulation, polymorphism, and reusability. However, COM was also designed to be compatible at the binary level and thus differs from a C++ object.As a programmer, you are aware that compiled programming languages such as C, C++, Pascal, and ADA are machine-dependent. As a binary object, a COM object concerns itself with how it interfaces with other objects. When not used in the environment of its creator, an interface is exposed that can be seen in the non-native environment. It can be seen because it is a binary object and therefore not machine-dependent. This does not require the host environment or an interacting object to know anything about the COM object. When the object is created in the womb of its mother application, COM does not concern itself with how that object interacts within it. This interaction is between the mother application and the child object.

When the object interacts with the rest of the world, however, COM is concerned about how to interface with that object. It’s important to note that COM is not a programming language; it is a binary standard that enables software components to interact with each other as objects. COM is not specific to any particular programming language. COM can work with any language that can support the binary layout of a COM object. It is a programming model to facilitate the programmability of this standard.

A programmatic view of OLE.

Permalink Leave a Comment

The Evolution of Component Technology

March 8, 2008 at 3:38 pm (COM, Extra) ()

You will begin your journey to understanding COM and DCOM by looking at the evolution of component technology. Although object-oriented technology has had an evolution all its own, a spinoff of object-oriented technology, termed component technology, has had its own evolution. The component technology evolution has a majority of its roots in the Microsoft Windows family of operating systems. Although there were other contributors to the component revolution with quasi-component–based development, using libraries of functions in FORTRAN, and Smalltalk classes, Microsoft has defined component-based technology as we see it today. This began with the custom control.

Custom Controls

The term control, or custom control, has been around since Windows 3.0, when it was first defined. A custom control is nothing more than a dynamic link library (DLL) that exports a defined set of functions. Unlike a DLL, a custom control can manipulate properties and handle the firing of events in response to user or programmatic input.

In the early days of Microsoft Windows, the Visual Basic (VB) development environment caught on in the development community, and component technology took off. VB programmers found that custom controls were necessary because they needed better ways to express the user interface of their applications. Many times, there was simply no way to perform a complex operation in Visual Basic. Unfortunately, or fortunately, depending on your perspective, these C language DLLs had no way of allowing Visual Basic to query the control for information on the properties and methods supported by the control. This made custom controls difficult to use in the Visual Basic development environment.

Visual Basic Extensions

In 1991, Microsoft unveiled the VBX. VBX stands for Visual Basic Extension. The idea was that these little reusable software components could be embedded in their container application. To everyone’s surprise, VBXs took off like wildfire. Companies cropped up all over the place, developing these little reusable software components. VBXs were able to provide a wide range of functionality, from a simple text label to a complex multimedia or communications control. They were written in C and C++ and provided a wide variety of capabilities that otherwise could not have been possible in a Visual Basic application. VBXs were extremely popular.

Because VBXs became popular, demand for them grew within the developer market. Soon developers wanted them for 32-bit applications and even on non-Intel platforms such as the DEC Alpha, RISC, Power PC, and the MIPS. Developers wanted to extend VBXs by using Visual Basic for Applications to connect VBXs with applications such as Access, PowerPoint, Excel, Project, and Word.

Unfortunately, VBXs are severely restricted. They were built on a 16-bit architecture that is not designed as an open interface. They were primarily designed to accommodate the Visual Basic environment. This made VBXs almost impossible to port to a 32-bit environment. Seeing the value and popularity of VBXs, Microsoft wanted to capitalize on this market. Microsoft was looking for an object-oriented architecture that was extensible and that supported a data-driven approach, as opposed to an application-driven approach. The result was OLE 1.0.

OLE 1.0

In 1991, Microsoft introduced a new specification called OLE 1.0. The acronym stood for object linking and embedding. OLE 1.0 was basically a method of handling compound documents. A compound document is a way of storing data in multiple formats—such as text, graphics, video, and sound—in a single document. At the time, object-oriented was the new programming buzzword, and the OLE 1.0 specification was a move toward a more object-oriented paradigm. Furthermore, OLE 1.0 was an effort to move toward a more document-centric approach, instead of an application-centric approach.

Unfortunately, OLE 1.0 was coldly received by software developers. Very few independent software vendors (ISVs) and corporations raced to embrace OLE 1.0 and to OLE-enable their applications. This reluctance to deploy OLE 1.0 in applications was mainly due to OLE 1.0 being very complex and having a steep learning curve. OLE 1.0 had to be coded using a very complex C application programming interface (API), which embodied programming concepts germane to OLE. These new concepts were foreign to most developers.

OLE 2.0

Undaunted by the limited success of OLE 1.0, Microsoft continued to strive to improve OLE. In 1993, Microsoft released the OLE 2.0 specification, which encompassed more than just compound documents. It sported an entire architecture of object-based services that could be extended, customized, and enhanced. The foundation of this services architecture was the Component Object Model. The services available through this architecture are

  COM
  Clipboard
  Drag and drop
  Embedding
  In-place activation
  Linking
  Monikers (persistent naming)
  OLE Automation
  OLE controls
  OLE documents
  Structured storage
  Uniform data transfer (UDT)

From a programmatic view, OLE 2.0 is a series of services built on top of each other, as shown in Figure 1.1. These services form an architecture of interdependent building blocks built on the COM foundation.

The foundation of OLE is COM, with each successive service built on the technologies of the others.

The release of OLE 2.0 had such an effect on standard ways of computing that it received two prestigious industry awards: a Technical Excellence award from PC Magazine and the MVP award for software innovation from PC/Computing. Adding to the OLE 2.0 success was a new and improved programming interface. Developers could now move to OLE-enabled applications much more easily. The OLE 2.0 services incorporate many principles embodied in object-oriented programming: encapsulation, polymorphism, and an object-based architecture. Further adding to the success of OLE 2.0 was the release in February 1993 of Visual C++ 1.0 with the Microsoft Foundation Class (MFC) Library version 2.0. MFC had wrapped the OLE API in a C++ class library, thus making it much easier for programmers to use the OLE services architecture.

Today, OLE is no longer the acronym for object linking and embedding. That term is obsolete. Now Microsoft refers to it as simply OLE, pronounced o-lay. Notice that no version number is attached to OLE anymore. Because OLE is an extensible architecture, it can be enhanced and extended without changing its basic foundation. A testimonial to this capability is OLE controls. OLE controls were not part of the original release of OLE. OLE controls were not added to the available OLE services until almost a year after the original release. In fact, objects created with OLE 1.0 still work and interact with modern OLE applications. However, their functionality is limited to the original 1.0 specification, so no need for versions exists. From here on, this chapter refers to OLE unless specifically outlining a feature of OLE 1.0 or 2.0.

Permalink Leave a Comment

New Features in EJB 3.1

March 4, 2008 at 1:20 pm (EJB, Extra) ()

Discussion

This series of articles is a preview of the changes the EJB 3.1 expert group is working on for the next version of the Java EE specification. The idea is to give you a head’s up on the changes as well as gather your feedback early so the expert group has the best chance of getting it right. EJB 3.0 brought simplicity to Java EE 5 by moving away from a heavyweight programming model. EJB 3.1 aims to build on those successes by moving further down the path of simplicity as well as adding a handful of much-needed features. In each article in this series, I will let you know about the progress made by the expert group over the next few months.

In this first article, I’ll cover the two features that have been discussed in detail so far–making interfaces optional for EJBs and Singleton Beans. I’ll also give you a look-ahead into the possible features yet to be discussed. Remember, none of this has been finalized yet; all of this is really just a peek into the inner workings of the JCP so that you have a chance provide early feedback.

EJB Interfaces are Optional

The very first change the expert group covered was removing the last remaining obstacle to making EJBs look just like POJOs in their simplest form by making Session Bean business interfaces optional.

Interface-based programming is clearly a useful technique in writing loosely-coupled, unit-testable applications. That is precisely why both EJB 2.1 and Spring promote the idea of component interfaces. In fact, at least one interface is required even for EJB 3.0 Session Beans (this is not a requirement for EJB 3.0 Message Driven Beans).

The trouble is that component interfaces are just a needless abstraction in a lot of circumstances. I can’t remember the times I silently cursed under my breath as I carried out the mechanical task of writing interfaces just because the framework needed it or the architect sitting in some ivory tower mandated it. A lot of times, just a regular Java object is really all you need for your foreseeable needs, especially if you don’t really do much unit testing and loose-coupling is just not enough of a concern for the application.

EJB 3.1 allows you to do just that. Now you do not need any interfaces for Session Beans, just like JPA Entities and Message Driven Beans. All you have to do is annotate a POJO with the @Stateless or @Stateful to get a fully functional EJB. Take a look at the example below modified from the Session Bean chapter in EJB 3 in Action:

@Stateless public class PlaceBidBean {

@PersistenceContext

private EntityManager entityManager;

public void placeBid (Bid bid) {

entityManager.persist(bid);

}

}

To keep things interesting, let’s add a few more features to this bargain-basement bean:

@Stateless @WebService

public class PlaceBidBean {

@PersistenceContext

private EntityManager entityManager;

@WebMethod public void placeBid (Bid bid) {

entityManager.persist(bid);

}

}

In the above example, we are using JAX-WS 2.0 to expose the simple little placeBid method as a web service. We’re also using JPA to persist a Bid entity. PlaceBidBean has the full range of Stateless Session Bean functionality available behind-the-scenes including pooling, thread-safety, component life-cycle, interceptors, security and declarative transactions. For example, as you might have guessed if you are familiar with EJB 3.0, the placeBid method is wrapped in a container-managed JTA transaction by default. RMI-based remoting will also be supported for these beans, although the exact semantics hasn’t been solidified yet.

Besides making it easy to get going with simple bean classes, dropping the interface requirements also makes using EJB 3.1 beans in WebBeans easy. Gavin King is leading the WebBeans JSR (JSR 299), largely inspired by the lessons in JBoss Seam. WebBeans is expected to make JSF, JPA and EJB 3.1 virtually seamless (no pun intended) and make Java EE 6 truly feel like a fully integrated stack.

The Singleton Beans are Here

EJB 3.1 Singleton Beans are the middleware equivalent of the GOF Singleton pattern. In the Java EE context, they are primarily used to store application-wide shared data.
Think about all the times you needed to cache some data in memory so you didn’t have to do the same old database lookups over and over again from different parts of the application. Neither Stateless Session Beans nor Stateful Session Beans meet this need. While Stateful Session Beans can maintain a session cache, it can’t really be shared amongst the application tier components very easily.

There are various ways of solving this problem now. The simplest way is to use static fields or GOF Singleton pattern POJOs. More complex strategies that can work across an application cluster include using the Servlet container’s application scope, JBoss Cache, OSCache, JCS and SwarmCache. Commercial solutions include Tangosol Coherence and Terracotta. While these solutions do work a majority of the time, they have a lot of weaknesses. Some are not thread-safe out of the box (static fields, Singleton POJOs), some are not transactional (Singleton POJOs, the Servlet application scope, OSCache, JCS, SwarmCache), none are remoteable and none have any security mechanisms. Other than the simplest solutions, all of them require the use of non-standard, third-party code. Enter EJB 3.1 Singletons.

The container is guaranteed to maintain a single shared instance of an EJB 3.1 Singleton. This means that Singletons can cache state across the application tier. Because it is an EJB, Singletons have all the middleware services you might expect–declarative transaction management, security, remoting, concurrency management, dependency injection, component life-cycle callbacks, interceptors and so on. Like all other EJBs, Singletons are simply annotated POJOs. Here is a simple example:

@Singleton

public class DiscountRateBean {

@PersistenceContext

private EntityManager entityManager;

private Rate rate;

@PostConstruct

private void init() {

rate = entityManager.find(Rate.class, 1);

}

@PreDestroy

private void destroy() {

entityManager.merge(rate);

}

public void setRate(Rate rate) {

this.rate = rate;

}

public Rate getRate() {

return rate;

}

}

The example is using JPA and bean life-cycle callbacks to load data on startup and save the data when the bean is destroyed (usually when the application is being shut-down). Any bean calling getRate and setRate is guaranteed access to the shared data stored in a single instance of DiscountRateBean. You’ll notice an interesting problem–any updates will be lost if the container does not get a chance to call the pre-destroy callback. We’ll see how to minimize this problem using cron-like timers in a future article.

By default, all Singleton methods are made thread-safe and transactional. This means that all multithreaded access to the bean is serialized and all methods are assumed to have a REQUIRED transaction attribute (do you think that these are sensible defaults? If not, why?). You can change transactional behavior using the @TransactionManagement and @TransactionAttribute annotations just like you would do for a Stateful or Stateless Session Bean. If you’ve ever done this sort of thing for a relatively large scale application, you know having both the getRate and setRate methods serialized can be a serious performance bottleneck. In reality, you simply need a read-lock on the getRate method while a read-write lock should be placed on the setRate method. You can do this by using the @ConcurrencyAttribute like so:

@Singleton

public class DiscountRateBean {

@PersistenceContext

private EntityManager entityManager;

private Rate rate;

@PostConstruct

private void init() {

rate = entityManager.find(Rate.class, 1);

}

@PreDestroy

private void destroy() {

entityManager.merge(rate);

}

@ConcurrencyAttribute(READ_WRITE_LOCK)

public void setRate(Rate rate) {

this.rate = rate;

}

@ConcurrencyAttribute(READ_LOCK)

public Rate getRate() {

return rate;

}

}

For those who are familiar with Doug Lea’s work, the READ_LOCK and READ_WRITE_LOCK terminology comes from java.util.concurrent. There are some application shared data that are just read-only. Any locking is really unnecessary in such cases. In such a case, you can create an unsynchronized Singleton like this:

@Singleton

@ConcurrencyAttribute(NO_LOCK) // READ_LOCK would also work…

public class DiscountRateBean {

@PersistenceContext

private EntityManager entityManager;

private Rate rate;

@PostConstruct

private void init() {

rate = entityManager.find(Rate.class, 1);

}

public Rate getRate() {

return rate;

}

}

One alternative to @ConcurrencyAttribute(READ_LOCK), @ConcurrencyAttribute(READ_WRITE_LOCK) and @ConcurrencyAttribute(NO_LOCK) being forwarded is @ConcurrencyReadLock, @ConcurrencyReadWriteLock and @ConcurrencyNoLock. To keep consistency with these low-level annotations, @TransactionAttribute would be broken up into @TransactionRequired, @RequiresNewTranscation, @TransactionNotSupported and so on. Some folks have pointed out that this mode of thinking begins to get into “annotation bloat” and adds a new source of complexity. This annotation granularity is also not consistent with Spring and C#.NET declarative transactions. Supporters of this model point out that it is easier to type than @ConcurrencyAttribute(READ_WRITE_LOCK), etc. What do you think?

It may also be entirely possible that you want to manage Singleton concurrency yourself and want the container to be uninvolved other than providing middleware services. This is supported through what is being called bean managed concurrency (a similar idea to bean managed transactions). Here is an example:

@Singleton

@ConcurrencyManagement(BEAN)

public class DiscountRateBean {

@PersistenceContext

private EntityManager entityManager;

private Rate rate;

@PostConstruct

private void init() {

rate = entityManager.find(Rate.class, 1);

}

@PreDestroy

private void destroy() {

entityManager.merge(rate);

}

public synchronized void setRate(Rate rate) {

this.rate = rate;

}

public synchronized Rate getRate() {

return rate;

}

}

Notice this time we are managing concurrency ourselves using the synchronized keyword. Since the container will not interfere, you are free to use whatever concurrency management mechanism you like, including but not limited to using the full power of the java.util.concurrent package. For now, the new concurrency management features are limited to EJB 3.1 Singletons, but they could be expanded to cover other bean types.

Singletons will also give you control over lazy/eager loading as well as explicit Singleton dependency management to address load ordering. We won’t discuss those features here although you are welcome to comment on that too. Although the specification does not cover clustering support, it is very likely that most vendors will make Singletons cluster-safe (just like Stateful Session Beans).

More EJB 3.1 Features

The two features discussed here are just the tip of the iceberg. There are a number of other very interesting features listed on the JSR agenda. Here are some of the most interesting ones:

  1. Support for direct use of EJBs in the servlet container, including simplified packaging options. The current thought is to allow EJBs in the WEB-INF/classes directory while allowing ejb-jar.xml to reside in the WEB-INF directory, just like the web.xml file. In a similar vein, you would be able to place an EJB jar into the WEB-INF/lib directory.
  2. EJB Timer Service enhancements to support cron-like scheduling, deployment-time timer creation, and Stateful Session Bean timed objects.
  3. Support for stateful web services via Stateful Session Bean web service endpoints.

In addition to these, there are a handful of features that are currently not on the JSR agenda but could be really great:

  1. Further simplification of JMS, JavaMail and database injected resources. For example, you should be able to inject MessageSenders, not just Queues and ConnectionFactory references. Gavin King is a major proponent of this enhancement.
  2. A Service Provider Interface (SPI) for EJB. This will make a number of innovative third-party integrations possible such as iBATIS, Spring, Acegi, Quartz or even Groovy Beans. Bill Burke, Mike Keith and I strongly support this feature.
  3. The ability to add EJB support to a lightweight servlet container like Tomcat. This would be similar to what is already available in the open source world in the form of Embedded JBoss, OpenEJB and EasyBeans. I haven’t brought this feature up to the group yet, but will if you think it is good.
  4. The ability to use local transactions in addition to JTA in EJB. I think this would be very useful for smaller web applications that really don’t need JTA.

A feature forwarded by Adam Bien, the standardization of JNDI mapping, is also particularly interesting as it will go a long way to enhancing portability across containers. What are your thoughts on this last list? Are the features useful? Should they be pushed harder? Are they more useful than what is on the current agenda?

Your Help is Needed

As you might be able to see, the expert group is trying hard to add useful features to EJB 3.1. We can only go so far on our own though… we need your feedback to tell us if we are on the right track or if we should be pursuing other paths. You can send your feedback directly to the JCP at jsr-318-comments@jcp.org. Feel free to CC me at rrahman@tripodtech.net so I am in the loop. In the coming months, I’ll try to present more features to you as we discuss them on the expert group. Until then, wish us good luck!

References

  1. JSR 318: Enterprise JavaBeans 3.1
  2. JSR 299: Web Beans
  3. JSR 316: Java EE 6

Permalink 1 Comment

EJB 3.0 Specification

March 2, 2008 at 7:15 am (EJB Specification, Extra) (, )

Download the Specification for EJB3.0

EJB 3.0 Core Contracts and Requirements

ejb30-jsr-220-ejb-core-contracts-and-requirements.pdf

EJB 3.0 Java Persistence API 1.0

ejb30-jsr-220-java-persistence-api.pdf

EJB3.0 Simplified API

ejb30-jsr-220-ejb-30-simplified-api.pdf

Permalink Leave a Comment

EJB 1.1 Specification

February 1, 2008 at 2:40 pm (EJB Specification, Extra) (, )

Enterprise Java Beans Specification for Version 1.1 is available here…

EJB 1.1 Specification

EJB 1.1 Specification

Compare this with Version 1.0

Permalink Leave a Comment

Next page »