Welcome!

Java IoT Authors: Elizabeth White, Mehdi Daoudi, Liz McMillan, Yeshim Deniz, Zakia Bouachraoui

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

@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
  • 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
    @CloudEXPO and @ExpoDX, two of the most influential technology events in the world, have hosted hundreds of sponsors and exhibitors since our launch 10 years ago. @CloudEXPO and @ExpoDX New York and Silicon Valley provide a full year of face-to-face marketing opportunities for your company. Each sponsorship and exhibit package comes with pre and post-show marketing programs. By sponsoring and exhibiting in New York and Silicon Valley, you reach a full complement of decision makers and buyers in ...
    While the focus and objectives of IoT initiatives are many and diverse, they all share a few common attributes, and one of those is the network. Commonly, that network includes the Internet, over which there isn't any real control for performance and availability. Or is there? The current state of the art for Big Data analytics, as applied to network telemetry, offers new opportunities for improving and assuring operational integrity. In his session at @ThingsExpo, Jim Frey, Vice President of S...
    In his keynote at 18th Cloud Expo, Andrew Keys, Co-Founder of ConsenSys Enterprise, provided an overview of the evolution of the Internet and the Database and the future of their combination – the Blockchain. Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settl...
    Two weeks ago (November 3-5), I attended the Cloud Expo Silicon Valley as a speaker, where I presented on the security and privacy due diligence requirements for cloud solutions. Cloud security is a topical issue for every CIO, CISO, and technology buyer. Decision-makers are always looking for insights on how to mitigate the security risks of implementing and using cloud solutions. Based on the presentation topics covered at the conference, as well as the general discussions heard between sessio...
    The Internet of Things is clearly many things: data collection and analytics, wearables, Smart Grids and Smart Cities, the Industrial Internet, and more. Cool platforms like Arduino, Raspberry Pi, Intel's Galileo and Edison, and a diverse world of sensors are making the IoT a great toy box for developers in all these areas. In this Power Panel at @ThingsExpo, moderated by Conference Chair Roger Strukhoff, panelists discussed what things are the most important, which will have the most profound e...
    The Jevons Paradox suggests that when technological advances increase efficiency of a resource, it results in an overall increase in consumption. Writing on the increased use of coal as a result of technological improvements, 19th-century economist William Stanley Jevons found that these improvements led to the development of new ways to utilize coal. In his session at 19th Cloud Expo, Mark Thiele, Chief Strategy Officer for Apcera, compared the Jevons Paradox to modern-day enterprise IT, examin...
    Rodrigo Coutinho is part of OutSystems' founders' team and currently the Head of Product Design. He provides a cross-functional role where he supports Product Management in defining the positioning and direction of the Agile Platform, while at the same time promoting model-based development and new techniques to deliver applications in the cloud.
    There are many examples of disruption in consumer space – Uber disrupting the cab industry, Airbnb disrupting the hospitality industry and so on; but have you wondered who is disrupting support and operations? AISERA helps make businesses and customers successful by offering consumer-like user experience for support and operations. We have built the world’s first AI-driven IT / HR / Cloud / Customer Support and Operations solution.
    LogRocket helps product teams develop better experiences for users by recording videos of user sessions with logs and network data. It identifies UX problems and reveals the root cause of every bug. LogRocket presents impactful errors on a website, and how to reproduce it. With LogRocket, users can replay problems.
    Data Theorem is a leading provider of modern application security. Its core mission is to analyze and secure any modern application anytime, anywhere. The Data Theorem Analyzer Engine continuously scans APIs and mobile applications in search of security flaws and data privacy gaps. Data Theorem products help organizations build safer applications that maximize data security and brand protection. The company has detected more than 300 million application eavesdropping incidents and currently secu...