Java IoT Authors: Yeshim Deniz, Carmen Gonzalez, Zakia Bouachraoui, Pat Romanski, Liz McMillan

Related Topics: Java IoT

Java IoT: Article

EJB 3.0 Preview

Part 1: The basic programming model

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.*;

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.

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:


   Session session = jndi.lookup("Session");
   Customer cust = session.getCustomerByName("Bill Burke");
   cust.setAddress("123 Boston Road");


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.

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");
   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.


  • www.jcp.org/en/jsr/detail?id=220
  • www.jboss.org/ejb3
  • More Stories By 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.

    Comments (5)

    Share your thoughts on this story.

    Add your comment
    You must be signed in to add a comment. Sign-in | Register

    In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.

    IoT & Smart Cities Stories
    Never mind that we might not know what the future holds for cryptocurrencies and how much values will fluctuate or even how the process of mining a coin could cost as much as the value of the coin itself - cryptocurrency mining is a hot industry and shows no signs of slowing down. However, energy consumption to mine cryptocurrency is one of the biggest issues facing this industry. Burning huge amounts of electricity isn't incidental to cryptocurrency, it's basically embedded in the core of "mini...
    The term "digital transformation" (DX) is being used by everyone for just about any company initiative that involves technology, the web, ecommerce, software, or even customer experience. While the term has certainly turned into a buzzword with a lot of hype, the transition to a more connected, digital world is real and comes with real challenges. In his opening keynote, Four Essentials To Become DX Hero Status Now, Jonathan Hoppe, Co-Founder and CTO of Total Uptime Technologies, shared that ...
    Every organization is facing their own Digital Transformation as they attempt to stay ahead of the competition, or worse, just keep up. Each new opportunity, whether embracing machine learning, IoT, or a cloud migration, seems to bring new development, deployment, and management models. The results are more diverse and federated computing models than any time in our history.
    At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
    At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
    Dion Hinchcliffe is an internationally recognized digital expert, bestselling book author, frequent keynote speaker, analyst, futurist, and transformation expert based in Washington, DC. He is currently Chief Strategy Officer at the industry-leading digital strategy and online community solutions firm, 7Summits.
    Digital Transformation is much more than a buzzword. The radical shift to digital mechanisms for almost every process is evident across all industries and verticals. This is often especially true in financial services, where the legacy environment is many times unable to keep up with the rapidly shifting demands of the consumer. The constant pressure to provide complete, omnichannel delivery of customer-facing solutions to meet both regulatory and customer demands is putting enormous pressure on...
    IoT is rapidly becoming mainstream as more and more investments are made into the platforms and technology. As this movement continues to expand and gain momentum it creates a massive wall of noise that can be difficult to sift through. Unfortunately, this inevitably makes IoT less approachable for people to get started with and can hamper efforts to integrate this key technology into your own portfolio. There are so many connected products already in place today with many hundreds more on the h...
    The standardization of container runtimes and images has sparked the creation of an almost overwhelming number of new open source projects that build on and otherwise work with these specifications. Of course, there's Kubernetes, which orchestrates and manages collections of containers. It was one of the first and best-known examples of projects that make containers truly useful for production use. However, more recently, the container ecosystem has truly exploded. A service mesh like Istio addr...
    Digital Transformation: Preparing Cloud & IoT Security for the Age of Artificial Intelligence. As automation and artificial intelligence (AI) power solution development and delivery, many businesses need to build backend cloud capabilities. Well-poised organizations, marketing smart devices with AI and BlockChain capabilities prepare to refine compliance and regulatory capabilities in 2018. Volumes of health, financial, technical and privacy data, along with tightening compliance requirements by...