YOUR FEEDBACK
Cloud Computing: Do You Really Want Your Data in the Cloud?
Don Dodge wrote: D Cheng, Of course in-house systems go down. What I am sa...


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
The advanced features Part 2

Digg This!

Last month's article on EJB 3.0 (Vol. 9, issue 11) focused primarily on the basic features of the specification. Part 2 dives much deeper into the specification to talk about more advanced features like dependency injection, dependent objects, secondary tables, and inheritance.

Dependency Injection
Dependency injection is the opposite of jndiContext.lookup(). The idea of dependency injection is that objects and services specify which resources and configuration values they require, and their container automagically injects these values. Dependency injection is supported for any session bean type and will also be supported in the greater J2EE specification in items such as servlets. This approach requires no JNDI lookup at all and can greatly simplify code. Let's look at an example.


@Stateful
public class ShoppingCartBean implements ShoppingCart
{
   @Inject private UserTransaction userTx;
   @Inject private EntityManager entityManager;

   private Petstore store;

   @EJB(name="petstore") public void setPetstore(Petstore store) {
      this.store = store;
   }

When an instance of ShoppingCartBean is allocated, the EJB container will look up the UserTransaction service and set the userTx variable. It will also get a reference to the EJB whose ejbName is "petstore" and call the setPetstore() method. Values can be injected either with an explicit field set or by calling a setter method. A great side effect of injection is that it becomes possible to test beans outside the context of a container. @Resource is another annotation for injecting things like DataSources and JMS connections.

Dependent Objects
The EJB 3.0 specification defines a full object/relational mapping for dependent value classes. You can map the properties of an aggregated value object in your entity to specific columns of the entity's table.


@DependentObject(access=AccessType.PROPERTY)
public class Address implements java.io.Serializable {

   private String street;
   private String state;
   private String city;

   public String getState() { return state; }
...
}

Your dependent value class can either have its properties defined as get/set methods or directly as fields. Next, define the mapping of a @DependentObject within your entity bean (see Listing 1).

Multi-Table Mappings
Many application developers find it necessary to map an entity bean to multiple tables within a database, especially when they have to map objects to a legacy data schema. EJB 3.0 provides mappings for this using the @SecondaryTable annotation.


@Entity
@SecondaryTable(name="ADDRESS", join={@JoinColumn(name="address_id")})
public class Customer {
...
   @Column(name = "street", secondaryTable = "ADDRESS")
   public String getStreet()
   {
      return street;
   }
...

The @SecondaryTable is defined as a class annotation and specifies the table's name as well as the columns to use to join the main and subtable together. The @JoinColumns of the secondary table must map directly to the primary key of the entity.

To map a specific property to the secondary table, specify the secondaryTable annotation member value from the @Column annotation.

Entity Inheritance
Another missing feature in EJB 2.1 is the ability to support inheritance and map a complex class hierarchy to a relational database. EJB 3.0 supports inheritance and polymorphic queries. Three types of inheritance mapping strategies are supported: one table per class hierarchy (SINGLE_TABLE), a join table per subclass (JOINED), and a distinct table per class (TABLE_PER_CLASS). Only SINGLE_TABLE is required by the EJB 3.0 specification, so we'll focus on an example covering that.

SINGLE_TABLE Strategy
The SINGLE_TABLE specifies that there should be one and only one table per class hierarchy. This table should have a column for each unique field for every class in the hierarchy. The table must have an additional column that identifies the object's type. By default, its type is a string with the default value being the fully qualified class name of the object stored. The @DiscriminatorColumn maps the object identity to a specific database column. The SINGLE_TABLE strategy is the optimal strategy for performance as the persistence engine doesn't have to do any complex joins when loading such an object. For example, say we have an Animal superclass entity bean, and a Dog subclass. The Java code would look like Listing 2.

The table mapping would be one gigantic table:

create table Animal (
ID Number,
TYPE varchar(255),
AVG_WEIGHT Number,
BREED varchar(255)
);

All entities that subclass from Animal can be queried polymorphically:

Query query = entityManager.createQuery("from Animal a where a.averageWeight > 10");

This query could return an instance of a Dog, Cat, Elephant, whatever entities that are currently defined in the Animal hierarchy.

Finally Usable
EJB 3.0 finally makes EJB persistence a reality. With EJB 2.1 entities you continually had to escape to direct JDBC, rely on vendor proprietary extensions, or move to an entirely different object/relational mapping strategy altogether. Features such as a full object relation mapping including a fully featured query language, inheritance, secondary tables, and dependent objects finally make the EJB specification.

With the use of annotations, XML deployment descriptors that have long been the bane of EJB developers can be completely removed if so desired by the developer.

All in all, EJB has come a long way since the 1.0 days and is morphing itself to the specifications of the community for which it was written.

References

  • JSR 220: Enterprise JavaBeans 3.0: www.jcp.org/en/jsr/detail?id=220
  • JBoss, EJB 3.0: 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.

    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