YOUR FEEDBACK
The Cloud Wars - Is Guitar Hero a Cloud?
Roland Judas wrote: I am following the cloud discussions for some months n...


2007 West
GOLD SPONSORS:
Active Endpoints
Your SOA Needs BPEL for Orchestration
BEA
Virtualized SOA: Adaptive Infrastructure for Demanding Applications
Nexaweb
Overcoming Bandwidth Challenges with Nexaweb
TIBCO
What is Service Virtualization?
SILVER SPONSORS:
WSO2
Using Web Services Technologies and FOSS Solutions
Click For 2007 East
Event Webcasts

2008 East
PLATINUM SPONSORS:
Appcelerator
Think Fast: Accelerate AJAX Development with Appcelerator
GOLD SPONSORS:
DreamFace Interactive
The Ultimate Framework for Creating Personalized Web 2.0 Mashups
ICEsoft
AJAX and Social Computing for the Enterprise
Kaazing
Enterprise Comet: Real–Time, Real–Time, or Real–Time Web 2.0?
Nexaweb
Now Playing: Desktop Apps in the Browser!
Sun
jMaki as an AJAX Mashup Framework
POWER PANELS:
The Business Value
of RIAs
What Lies Beyond AJAX?
KEYNOTES:
Douglas Crockford
Can We Fix the Web?
Anthony Franco
2008: The Year of the RIA
Click For 2007 Event Webcasts
SYS-CON.TV
TOP THREE LINKS YOU MUST CLICK ON


EJB 3.0 Preview
Part 1: The basic programming model

Digg This!

This article is part one of a two-part series on the new Enterprise JavaBeans (EJB) 3.0 specification. Prior knowledge of J2EE/EJB will enable a better reading experience. Part 1 focuses on the basic programming model of EJB 3.0. Part 2 will focus on more advanced features like dependency injection and complex persistence mappings (entity inheritance and multitable mappings).

Over the past 15 years, each revision of middleware specifications like DCE, CORBA, and J2EE evolved into a larger, more complex definition of new functionality and bloatware. Rarely has a standards-based specification stepped back and actually tried to make development easier for its user base.

Until now that is. The mandate of the EJB 3.0 expert group to focus on ease of use and simplification is a refreshing unprecedented change in a standards body. This article focuses on the goals of EJB 3.0 and walks you through the new model for session and entity beans.

The Difficulties of EJB 2.1
There are a lot of problems in EJB 2.1 that make it difficult to develop EJBs. XML deployment descriptors have continually been the bane of developers. Tools like XDoclet have helped alleviate some but not all of the complexity. Removing these files would go a long way toward making things simpler. One big annoyance in EJB is the sheer verbosity of the API. You have to create a number of interfaces and classes to implement one EJB: a remote and a local interface, a remote and local home interface, and finally a bean class. Your bean classes have to implement EJB interfaces that have numerous callback methods like ejbCreate or ejbPassivate that are often never even used at all as part of the application logic. Yet another complaint is that EJBs are completely untestable outside the context of the container as components like entity beans are abstract classes. Finally, EJBQL in its current form is so significantly hobbled that developers continually have to escape to straight JDBC and SQL, or ditch their CMP efforts entirely and replace them with something like Hibernate.

Fortunately, the EJB 3.0 specification is working to address most of these problems. Let's take a look at how this is being accomplished.

Deployment Descriptors
JDK 1.5 has a new feature called annotations defined in the JSR-175 JCP specification. Annotations allow you to define configuration information as an interface, then apply instantiations of this configuration as metadata attached to a class, method, field, constructor, package, or parameter. For those familiar with XDoclet, it is very similar except the metatags are typed syntax that is checked by the Java compiler. This metadata is even available at runtime. The EJB 3.0 specification uses annotations so that you can declare your EJB metadata directly within the bean class.


import javax.ejb.*;

@Stateful
public class ShoppingCartBean implements ShoppingCart
{
   @Tx(TxType.REQUIRED) @MethodPermission({"customer"})
   public void purchase(Product product, int quantity) {...}


   @Remove void emptyCart() {...}
}

The @Stateful annotation marks the ShoppingCartBean as a stateful session bean. @Tx denotes transaction demarcation, while @MethodPermission defines role-based security for the bean method. EJB 3.0 provides annotations for every type of metadata so that no XML descriptor is needed and you can deploy your beans simply by deploying a plain old JAR into your application server. This doesn't mean that XML completely disappears; it becomes optional. If you don't like to expose infrastructure metadata directly in application logic, all annotation types are overridable in an XML deployment descriptor.

Simplified API
The stateful session bean example above is complete. You'll notice that without the annotations, ShoppingCartBean is a plain old Java object (POJO). It does not have to extend javax.ejb.SessionBean, or implement any of the callback methods like ejbPassivate(), ejbCreate(), ejbRemove(), etc. Session beans must also implement at least one interface. What's great about this interface is that it, too, is plain Java.


public interface ShoppingCart
{
   public void purchase(Product product, int quantity);
   public void emptyCart();
}

Another goal of EJB 3.0 is to provide common sense defaults. A session bean that implements only one interface treats that interface as a local interface by default. If you wish to make your EJB remote, you must explicitly tag the interface as such.


@Remote interface ShoppingCart
{
   public void purchase(Product product, int quantity);
   public void emptyCart();
}

Remote interfaces do not have to extend javax.ejb.EJBObject, nor do any of the methods have to throw a RemoteException as in the EJB 2.1 specification. EJB 3.0 tries to remove the dependencies on RMI APIs.

Callbacks a la Carte
The EJB 2.1 spec required you to implement the interfaces javax.ejb.SessionBean or javax.ejb.EntityBean. Methods like ejbCreate(), ejbPassivate(), and ejbActivate() were never used in your application and just cluttered up your code. In EJB 3.0 you can use these methods a la carte on an as-needed basis.

Homeless
Home interfaces have been completely removed for all EJB types. They never made much sense for stateless beans, and had only limited use for stateful sessions. Looking up a session bean gives you a proxy that you can immediately use to invoke on the session. Every time a stateful bean is referenced from JNDI, a new instance is created. It is assumed that the first method called should initialize the bean. Methods marked as @Remove will destroy the stateful session after the annotated method has completed. Entity beans are created, removed, and queried through the new EntityManager interface which will be described later in this article.

Entity Beans
Entity beans are by far the biggest change in EJB 3.0; they received a complete overhaul in this version of the specification. One thing that the EJB 3.0 expert group realized is that a one-size-fits-all approach to persistence does not produce a very usable API. For instance, the portability of 2.1 entity beans is nonexistent as different vendors have different database mappings. EJB 3.0 focuses on an object-to-relational (O/R) mapping that supports inheritance, multitable mappings, join-tables, a fully functional query language, and SQL escapes. These are all the things you would expect from an O/R persistence engine. Another important change to entity beans is that they are pure plain Java objects and can no longer be remotely accessed, or provide transaction or role-based security boundaries. This approach to a pure POJO has many advantages -- the biggest being that you can detach and reattach entities to persistence storage. We'll see more on that later in this article.

Let's walk through Listing 1. As you can see, the order entity bean is a plain Java object. The @Table annotation specifies the table name. The class contains private fields that represent the state of the bean, while get and set methods wrap the access to these fields. The column mappings are applied as annotations on the get methods of the class. If you don't like this approach, you can declare these mappings on the fields. @Id is used to specify the primary key field. @Column specifies the column mapping while the @OneToOne and @OneToMany persistent fields use @JoinColumn to specify the foreign key column of the related table. OneToMany and ManyToMany relationships are specified as a Collection generic.

All in all, the O/R mapping was designed to be compact yet flexible with intuitive defaults. For instance, if you were relying on the container to do auto-generation of your database tables, only the @Entity and @Id annotations would be required as the rest of the persistence metadata would have well-known defaults.

Interacting with Entity Beans
Entity beans no longer have homes. They are created as plain Java objects using Java's new operator and all interaction between persistence storage and application code is handled by a new service called the EntityManager. Listing 2 shows an example of this.

Attachment, Detachment, and Reattachment
What is interesting about the checkout() method of our ShoppingCart bean is that it returns the order object that it created. In EJB 3.0, the old antipattern of value objects is not needed because persistent objects can be attached, detached, and reattached to persistence storage. For example, you could have a remote client that created all the OrderItems and the order object on the client-side, send the order object over the network in a remote EJB call, and have the EntityManager create the order, or if you're updating, merge the changes to the persistent object. Because they are plain Java objects, entity beans can be used in <jsp:useBean> tags and stored in an HTTP session. You can imagine a five-step wizard that allocates a group of entity beans that holds the state of the wizard, then, when the wizard completes, interacts with the EntityManager to create all the persistent data. The programming model becomes much simpler as you have one object that you can pass around from tier to tier to handle your creates and updates. Here's an example of doing updates remotely:

Client


   Session session = jndi.lookup("Session");
   Customer cust = session.getCustomerByName("Bill Burke");
   cust.setAddress("123 Boston Road");
   cust.setCity("Concord");
   cust.setState("MA");
   cust.setZip("02143");

   session.updateCustomerInfo(cust);

In the above example, the remote client gets access to a customer ob-ject through a method on a session bean. All the setter methods are done locally to an instance of customer in the local VM. When the client is finished updating the customer locally, it sends the customer over the network to the remote session bean to be updated in persistent storage. Listing 3 shows how the session bean would be implemented.

The getCustomerByName() method simply searches for a customer of a given name. When the customer object is returned, it is detached from the persistence engine and is no longer associated or managed by the EntityManager. The updateCustomerInfo() method receives the fully modified customer and reattaches the object by calling the merge() method. This causes the EntityManager to do an update on the customer's row in the database.

Querying
Unlike the EJB 2.1 specification, 3.0 has full support for dynamic queries. You can build a query object through EntityManager.createQuery(), then interact with the query object to set page sizes and arguments.


   Query query = entityManager.createQuery("from Order o where o.grandTotal > 5000.00");
   query.setMaxResults(50);
   return query.listResults();

EJBQL is now a fully featured query language that mirrors the functionality of SQL. Support for group by, having, inner and outer join, subqueries, and bulk update and delete has been added. Also, queries can now return more than one value as well as a list of objects. One of my favorite features of the new query language is the ability to project results onto any arbitrary Java object by using a constructor directly in the query. For instance, say you wanted a page on a petstore application that displayed a report on sales divided by geographical area. The query might look something like this:


SELECT new GeographicalReport(c.state, sum(o.grandTotal)) From Customer c
join Order.customer Customer
GROUP BY c.state

GeographicalReport is not an entity bean, but rather a plain Java object. The entity manager would execute the query and allocate a GeographicalReport object per row returned in this example. Instead of iterating though a potentially large untyped result set, you can have the query manager automatically populate the data structures you need.

Coming Soon
The first draft of the EJB 3.0 specification was announced in June at JavaOne. As is, it is a good first step at simplifying the EJB programming model and fixing some of the deficiencies in the persistence model. Although the specification is not due to be finished until next year, some vendors have committed to providing early-access downloads so that you can play with this new technology. All in all, these are exciting times for EJB.

Next month we will dive into more advanced features of EJB 3.0.

References

  • www.jcp.org/en/jsr/detail?id=220
  • www.jboss.org/ejb3
  • About Bill Burke
    Bill Burke is chief architect of JBoss Inc., member of the EJB3 expert group, and co-author of the JBoss 4.0 Workbook in O'Reilly's Enterprise JavaBeans, 4th Edition.

    EJB3 wrote: Great series Bill, it's really good to see a member of the expert group taking time and trouble like this. Thank you.
    read & respond »
    Carl wrote: Bill Burke indicates that instead of having to do a home interface create to get a session bean instance, you just do a JNDI lookup. That's much easier than the 2.x pattern! However a JNDI lookup is usually pretty expensive. That's why most of use the home factory pattern and cache the results of the JNDI lookup. Is this going to get less expensive under 3.0?
    read & respond »
    Hello Chuck wrote: The code listing was one line before the feedback you typed up... :-))
    read & respond »
    Chuck wrote: Duh - found them.
    read & respond »
    Chuck wrote: Where is Listing 1??
    read & respond »
    LATEST JAVA STORIES & POSTS
    Saving Your Investment: Transforming J2EE applications into Web 2.0 using GWT
    The pressure is on to keep pace with Web 2.0 entrants into the marketplace. Rewriting is expensive; adding AJAX widgets results in a complex, unmaintainable application. Both require you to hire scarce JavaScript developers. Google Web Toolkit -- the SDK that allows you to write
    WSRP Really Works! - Part 2
    A standard from OASIS called Web Services for Remote Portlets (WSRP) is used so portlets can be decoupled from a portal. In part one (JDJ, Volume. 13, issue 3) of this article, we introduced the relevant standards and specifications and then demonstrated WSRP's capabilities by co
    Adobe's Kevin Lynch and Microsoft's Scott Guthrie to Keynote AJAX World RIA Conference & Expo
    Two of the biggest launches in Rich Internet Application history took place in 2007/2008 when Adobe launched AIR 1.0 in February '08 and Microsoft launched Silverlight (September '07). At the 6th International AJAXWorld RIA Conference & Expo in October SYS-CON Events is delighted
    Sun Expects Q4 Earnings Above Estimates
    On Tuesday evening Sun issued a fourth-quarter guidance range largely above analysts' estimates. The company pre-announced that revenue for its fiscal fourth quarter ended June was $3.725 billion to $3.8 billion, with gross margin in the 44-45% range. Sun expects non-GAAP profits
    Virtualization Conference Keynote Webcast Live on SYS-CON.TV
    Brian Stevens, the Chief Technology Officer and Vice President of Engineering of Red Hat, delivered his Virtualization Keynote 'The Future of the Virtual Enterprise' at SYS-CON's Virtualization Conference & Expo 2007 West in San Francisco. 'Virtualization is the hottest subject
    The Beauty of JavaScript
    JavaScript is one of the most interesting and misunderstood programming languages in common use today. Most developers will go their entire careers without realizing its full potential. It's not often that you get a language that supports the feature set that JavaScript does, whi
    SUBSCRIBE TO THE WORLD'S MOST POWERFUL NEWSLETTERS
    SUBSCRIBE TO OUR RSS FEEDS & GET YOUR SYS-CON NEWS LIVE!
    Click to Add our RSS Feeds to the Service of Your Choice:
    Google Reader or Homepage Add to My Yahoo! Subscribe with Bloglines Subscribe in NewsGator Online
    myFeedster Add to My AOL Subscribe in Rojo Add 'Hugg' to Newsburst from CNET News.com Kinja Digest View Additional SYS-CON Feeds
    Publish Your Article! Please send it to editorial(at)sys-con.com!

    Advertise on this site! Contact advertising(at)sys-con.com! 201 802-3021

    SYS-CON FEATURED WHITEPAPERS

    SPONSORED BY INFRAGISTICS
    SOA in a JVM: OSGi Service Platform - A Dynamic Component System for Java
    There are many forces that influence technological evolution. After a decade of building enterprise
    AJAX and Enterprise RIA Tools - JSF, Flex, and JavaFX
    2008 is going to be an important year for Rich Internet Applications. Most organizations are deliver
    Final Voting Phase on OpenAjax Browser Wishlist
    The OpenAjax Alliance is developing an Ajax industry wishlist for future browsers, using a dedicated
    AJAX World RIA Conference News - Netflix UI Guru To Present on Crafting Rich Web Interfaces
    In every field of design one of the first things students do is learn from the work of others. They
    Infragistics Releases CTP UI Components for Microsoft Silverlight Beta 2
    Infragistics announced the availability of two Community Technology Preview (CTP) User Interface (UI
    Yahoo User Interface 2.5.2 Released
    The YUI development team has released version 2.5.2; you can download the new release from SourceFor
    ADS BY GOOGLE
    BREAKING JAVA NEWS
    Domark International, Inc. Completes Its Acquisition of Javaco, Inc.
    Domark International, Inc. (OTCBB:DOMK) announced today that it has completed its acqui