Welcome!

Java IoT Authors: Pat Romanski, Liz McMillan, Elizabeth White, Yeshim Deniz, Frank Lupo

Related Topics: Java IoT

Java IoT: Article

The Delegation-Managed Persistence Entity Bean

A composite entity bean for a new generation

With the introduction of the EJB 2.0 specification, the classic composite entity bean design pattern became outdated overnight. In this article, I present a new pattern that can serve as a proper replacement. This pattern, called Delegation-Managed Persistence bean (DMP bean), allows developers to represent objects that span multiple database tables. DMP beans provide a better solution than the original Composite EJB pattern without making you roll your own persistence mechanism.

Let's start with the basics. Why are composite entity beans required, anyway? The problem is that in many cases (depending on your application server and database), beans with container-managed persistence (CMP entity beans) can span only a single database table. However, in many enterprise databases, a single conceptual object is stored in numerous independent tables. The standard practice for solving this, in the days of EJB 1.x, was using bean-managed persistence (BMP entity beans). With BMP beans, the developer provides his or her own implementation for storing the bean to, and loading it from, the persistent storage (namely the database). This is a tiresome, repetitive, and error-prone job, and it often sacrifices portability for the sake of performance. Portability, for example, could be lost if nonstandard SQL statements (or even stored procedures) are used. The old composite entity bean pattern was basically just a bean that knew how to load itself from several tables using as many JDBC queries as needed, and likewise knew how to store itself to these tables, again using JDBC. This allowed developers to bypass the CMP limit of one table per bean, while providing a proper object-oriented representation of the notion represented by the bean.

A simple example would be the notion of client in an enterprise application, where information about each client is stored in several distinct tables - one table contains contact information, another contains the client's credit status, and so on. From an object-oriented point of view, we're interested in a single Client class that provides access to all the information stored in all the individual tables.

With the introduction of the EJB 2.0 standard, the common solution to such problems became using container-managed relationships (CMRs). A CMR allows a CMP entity bean to maintain a "relationship" to other CMP beans as long as these relationships are represented in the underlying database as foreign keys. This allows you to define fine-grained entity objects, rather than coarse-grained composite beans. The main problem with fine-grained objects in EJB 1.x was the price of remote method invocations. But now that entity beans are strongly encouraged to use the new local interface feature, this becomes a nonissue. Application clients access session beans, following the Session Façade design pattern, and these session beans access the entity beans using their local home and component interfaces.

This sounds like a good solution, but it suffers from two serious drawbacks. First, as noted earlier, the use of CMRs limits the usability of this solution to those composite objects that, in their database representation, use foreign keys. While this is indeed common, it is not always the case. The second problem is more bothersome: the fine-grained entities provide an accurate depiction of the database tables, rather than a high-level, object-oriented view of the concepts with which we deal.

True, the application clients do not deal with these low-level objects, but rather with high-level services offered by the session beans; but this is simply a shift of focus. The session beans now serve as clients to the entity beans. These session beans often contain key parts of the application logic - and it's expressed using a low-level view of the object model. This is unsatisfactory, and in fact contradictory to the original notion of entity EJBs as a high-level object model for the application data.

The original Composite Entity bean pattern solved this problem by providing a high-level view of the data, but at a great price, namely the tiresome and error-prone work required to create these beans. So allow me to present the new Delegation-Managed Persistence (DMP) bean pattern, which provides the same functionality and high-level view as composite entity beans do, while being easy to create and maintain, and taking full advantage of container-managed persistence.

The new pattern will be described here using the simple case of a composite bean Item, which is stored across two database tables: ITEM_DATA_1 and ITEM_DATA_2. We'll assume that each Item occupies one row in each of these two tables. Naturally, the pattern is applicable to a much wider range of cases.

We begin by defining two CMP entity beans, ItemData1 and ItemData2, over the two database tables. These are the DMP bean's underlying fine-grained entities, and we'll refer to them as Item's component beans.

Next we define the Item class as a BMP entity bean. Don't worry, while defined as a BMP bean, our DMP bean will not really have to manage its own persistence issues.

In the bean class, we define a field for each of the component beans: these fields are the component bean references and Item has two such fields. We also define the component key references as one additional field per component bean; the type of these fields is the type of each component bean's primary key class.

Again for the sake of simplicity, we will assume that both ItemData1 and ItemData2 use java.lang.Integer for their primary key classes. So Item's bean class definition begins like this:

public class ItemBean implements EntityBean {
// Component bean references:
private ItemData1Local itemData1;
private ItemData2Local itemData2;

// Component key references:
private Integer itemData1Key;
private Integer itemData2Key;

Note that, true to the spirit of EJB 2.0, we access the underlying fine-grained entities via their local component interfaces. As you can probably guess, the component key references are maintained so we can lazily load the beans on a per-need basis. Two private methods, getItemData1() and getItemData2(), will be used internally to access the component bean references. The pseudo-code for the first of these methods would be:

private ItemData1Local getItemData1() {
if (itemData1 == null) {
// find local home, probably using a home factory
ItemData1LocalHome home = ...;

itemData1 = home.findByPrimaryKey(itemData1Key);
}

return itemData1;
}

In itself, Item's bean class does not contain any fields for representing bean attributes. Any getter or setter method for loading or changing attribute values is delegated to the underlying component beans via the component references, like this:

public getSomeAttribute() {
return getItemData1().getSomeAttribute();
}

Like attributes, any business operations defined in the component beans can also be made available in the higher-level DMP bean using delegation. Yet we can also provide new, more complex features that involve accessing several attributes or several business methods from one or more of the component beans. We are, in effect, providing a high-level view of the single business notion stored across multiple database tables.

The Primary Key Class
The primary key for a DMP should be a composite key: a simple Java class that includes (as fields) the primary keys for every component bean class. In our example, the ItemKey class would have two fields of type Integer, one for ItemData1's key and the other for ItemData2's. All normal primary key rules apply here - make sure the class is serializable, has proper equals() and hashCode() methods, and so forth. Getters and setters for the internal keys are also in order.

Loading and Storing DMPs
In most BMPs, the key life-cycle methods - ejbLoad() and ejbStore() - are complex beasts, accessing one or more tables in the database directly by means of JDBC. Surprisingly, in DMP beans, ejbStore() is completely empty, while ejbLoad() is extremely simple and involves no manual database access.

No implementation is required for ejbStore() since any update is delegated to the component CMPs, which by their very nature allow the container to manage their persistence needs.

As for ejbLoad(), in this method the bean obtains its composite primary key from its entity context object and checks if any of the internal keys is different from the privately maintained component key references. If a component's key was changed, we must store the new value, and we can no longer assume that the local reference to that object is valid. To invalidate the maintained reference, we simply nullify it, and it will be loaded again when needed due to the lazy evaluation mechanism detailed earlier. So in our example, ejbLoad() would look like Listing 1.

While technically a BMP, the composite bean does not manage its own persistence: it indirectly delegates it to the container. This is why it was named "Delegation-Managed Persistence bean" or "DMP bean" in the first place.

Passivation and Activation of DMP Beans
No special actions are required when DMP beans are passivated or activated. Still, it could help the container better manage its resources if the component references and component key references are all nullified in ejbPassivate().

Creating, Finding, and Removing DMP Beans
Perhaps the most sensitive part of this pattern is the implementation of the ejbCreate...() and ejbFind...() life-cycle methods. The last remaining life-cycle method, ejbRemove(), is rather simple to implement: just remove each of the component CMPs in turn. Make sure ejbRemove() has the REQUIRES transaction attribute, so if the removal of any of the component beans fails, no removal will take place.

Each ejbFind...() method should return the composite primary key type. This is basically done by finding each of the relevant component CMPs (via whatever finder methods they provide in their own local home interfaces, and possibly using CMRs between these CMPs), and then composing the required primary key from its components (the primary keys of the component CMPs).

Slightly more complex is the case of finders that return collections. While it is possible to retrieve the relevant collections of composing keys, and then iterate over them in order to create a new collection of composite keys, this could be highly ineffective. One solution is to create a lazy collection mechanism that keeps the collections of composing keys, and delves into them only when an iterator is used (a lazy collection). Bear in mind, however, that (depending on your application server software) collections returned by local home interfaces of CMP beans are often lazy collections themselves, and are invalidated as soon as the transaction that created them is over. In such cases, there is no option other than to create the whole collection immediately inside the DMP bean's finder method.

But DMP beans can do more than rely on the finder methods provided by their composing beans. The finder methods are one place where it does make sense to use JDBC directly in DMP beans. Using raw SQL, you can create finders that are too complex, ineffective, or downright impossible to implement using EJB QL. Thus, if your high-level business notion, which spans multiple database tables, suggests high-level search criteria that cannot be expressed by simple searches on individual tables, you can make these searches available without manually iterating over collections of fine-grained objects.

Finally, as for ejbCreate...() methods, these should create the relevant component CMPs (using their own create...() methods from the local home interface), and maintain the resulting local references in the DMP bean's fields. Again, as with ejbRemove(), the entire creation process should normally be enclosed within a single database transaction.

Conclusion
The pattern presented here allows developers to easily create a high-level object-oriented view of complex business objects, which cannot be represented using CMP entity beans due to mapping limitations. These high-level objects can then be used by their clients (normally session beans that would access them via a local interface), simplifying the client code since it no longer has to be aware of the internal structure of these potentially complex objects. While overcoming the limitations of CMP entities, Delegation-Managed Persistence Beans do not necessitate the creation of complex persistence code, since they take full (if indirect) advantage of the automated persistence services offered by the container.

More Stories By Tal Cohen

Tal Cohen is a consultant specializing in J2EE and related technologies. Until
recently, he had worked as a researcher in IBM's Haifa Research Labs. He can
be contacted at [email protected]

Comments (5) View Comments

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.


Most Recent Comments
R Stento 03/04/04 01:02:16 PM EST

Chris M raises a good issue that users are still left with the implementation of the create and find methods. The value of O/R mapping tools that generate the implementation for persistent objects becomes apparent when one tackles a real-world application with hundreds of objects and complex relationships. Persistence Software (and other vendors) offer such tools. From our customer''s experiences, code generation can cut development time and costs by 20 - 50% and really deliver on one of the promises of J2EE - allow developers to concentrate on the business-critical logic of their application.

Chris M 02/13/04 12:26:28 PM EST

Other than the suggested name "DMP" bean there is nothing new in here and the pattern leaves more importan issues like querying to be solved by the users.
Another thing is that this approach could be implemented and I read articles in the past about it not only with EJB 2.0 but 1.0 too
So what''s really new in here?!

David T. 02/13/04 10:55:42 AM EST

Excellent article. It is a valid approach to overcoming the single-table limitation of CMP without doing all of the work normally involved in BMP. This approach helps the developer of the DMP bean still benefit from CMP.

Unfortunately the DMP bean still looks like a BMP bean to the rest of the system. In other words, the client cannot use EJBQL, the DMP cannot participate in CMR, etc.

The DMP pattern is effective at overcoming one weakness in the EJB specification and it is efficient from a bean developer viewpoint. It cannot overcome the weakness in EJB from an architectural viewpoint however.

Without a proper object query language, such as OQL, the entity bean developer is forced to constantly write new use-case specific finder methods as the system evolves. This creates challenges throughout the SDLC.

Look around, there are much better persistence frameworks available that avoid EJB entity beans altogether.

F. Degenaar 02/13/04 04:07:03 AM EST

Your article is most welcome. It''s especially helpful when having temporal data in two tables (current data vs. historical data).
The problems with finders could be solved be the fat key pattern (http://www.theserverside.com/patterns/thread.jsp?thread_id=4540).
Regards
Fokko

Kamyar Varzandeh 02/13/04 01:22:52 AM EST

Excellent article. Consider submitting the pattern to Sun''s Core J2EE patterns.

@ThingsExpo Stories
Coca-Cola’s Google powered digital signage system lays the groundwork for a more valuable connection between Coke and its customers. Digital signs pair software with high-resolution displays so that a message can be changed instantly based on what the operator wants to communicate or sell. In their Day 3 Keynote at 21st Cloud Expo, Greg Chambers, Global Group Director, Digital Innovation, Coca-Cola, and Vidya Nagarajan, a Senior Product Manager at Google, will discuss how from store operations...
Nordstrom is transforming the way that they do business and the cloud is the key to enabling speed and hyper personalized customer experiences. In his session at 21st Cloud Expo, Ken Schow, VP of Engineering at Nordstrom, will discuss some of the key learnings and common pitfalls of large enterprises moving to the cloud. This includes strategies around choosing a cloud provider(s), architecture, and lessons learned. In addition, he’ll go over some of the best practices for structured team migrat...
With major technology companies and startups seriously embracing Cloud strategies, now is the perfect time to attend 21st Cloud Expo October 31 - November 2, 2017, at the Santa Clara Convention Center, CA, and June 12-14, 2018, at the Javits Center in New York City, NY, and learn what is going on, contribute to the discussions, and ensure that your enterprise is on the right path to Digital Transformation.
SYS-CON Events announced today that Datera will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Datera offers a radically new approach to data management, where innovative software makes data infrastructure invisible, elastic and able to perform at the highest level. It eliminates hardware lock-in and gives IT organizations the choice to source x86 server nodes, with business model option...
Recently, REAN Cloud built a digital concierge for a North Carolina hospital that had observed that most patient call button questions were repetitive. In addition, the paper-based process used to measure patient health metrics was laborious, not in real-time and sometimes error-prone. In their session at 21st Cloud Expo, Sean Finnerty, Executive Director, Practice Lead, Health Care & Life Science at REAN Cloud, and Dr. S.P.T. Krishnan, Principal Architect at REAN Cloud, will discuss how they bu...
Infoblox delivers Actionable Network Intelligence to enterprise, government, and service provider customers around the world. They are the industry leader in DNS, DHCP, and IP address management, the category known as DDI. We empower thousands of organizations to control and secure their networks from the core-enabling them to increase efficiency and visibility, improve customer service, and meet compliance requirements.
Digital transformation is changing the face of business. The IDC predicts that enterprises will commit to a massive new scale of digital transformation, to stake out leadership positions in the "digital transformation economy." Accordingly, attendees at the upcoming Cloud Expo | @ThingsExpo at the Santa Clara Convention Center in Santa Clara, CA, Oct 31-Nov 2, will find fresh new content in a new track called Enterprise Cloud & Digital Transformation.
SYS-CON Events announced today that N3N will exhibit at SYS-CON's @ThingsExpo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. N3N’s solutions increase the effectiveness of operations and control centers, increase the value of IoT investments, and facilitate real-time operational decision making. N3N enables operations teams with a four dimensional digital “big board” that consolidates real-time live video feeds alongside IoT sensor data a...
SYS-CON Events announced today that NetApp has been named “Bronze Sponsor” of SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. NetApp is the data authority for hybrid cloud. NetApp provides a full range of hybrid cloud data services that simplify management of applications and data across cloud and on-premises environments to accelerate digital transformation. Together with their partners, NetApp emp...
Smart cities have the potential to change our lives at so many levels for citizens: less pollution, reduced parking obstacles, better health, education and more energy savings. Real-time data streaming and the Internet of Things (IoT) possess the power to turn this vision into a reality. However, most organizations today are building their data infrastructure to focus solely on addressing immediate business needs vs. a platform capable of quickly adapting emerging technologies to address future ...
SYS-CON Events announced today that Avere Systems, a leading provider of hybrid cloud enablement solutions, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Avere Systems was created by file systems experts determined to reinvent storage by changing the way enterprises thought about and bought storage resources. With decades of experience behind the company’s founders, Avere got its ...
SYS-CON Events announced today that Avere Systems, a leading provider of enterprise storage for the hybrid cloud, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Avere delivers a more modern architectural approach to storage that doesn't require the overprovisioning of storage capacity to achieve performance, overspending on expensive storage media for inactive data or the overbui...
SYS-CON Events announced today that IBM has been named “Diamond Sponsor” of SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California.
SYS-CON Events announced today that Ryobi Systems will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Ryobi Systems Co., Ltd., as an information service company, specialized in business support for local governments and medical industry. We are challenging to achive the precision farming with AI. For more information, visit http:...
High-velocity engineering teams are applying not only continuous delivery processes, but also lessons in experimentation from established leaders like Amazon, Netflix, and Facebook. These companies have made experimentation a foundation for their release processes, allowing them to try out major feature releases and redesigns within smaller groups before making them broadly available. In his session at 21st Cloud Expo, Brian Lucas, Senior Staff Engineer at Optimizely, will discuss how by using...
In this strange new world where more and more power is drawn from business technology, companies are effectively straddling two paths on the road to innovation and transformation into digital enterprises. The first path is the heritage trail – with “legacy” technology forming the background. Here, extant technologies are transformed by core IT teams to provide more API-driven approaches. Legacy systems can restrict companies that are transitioning into digital enterprises. To truly become a lead...
SYS-CON Events announced today that Daiya Industry will exhibit at the Japanese Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Ruby Development Inc. builds new services in short period of time and provides a continuous support of those services based on Ruby on Rails. For more information, please visit https://github.com/RubyDevInc.
SYS-CON Events announced today that CAST Software will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. CAST was founded more than 25 years ago to make the invisible visible. Built around the idea that even the best analytics on the market still leave blind spots for technical teams looking to deliver better software and prevent outages, CAST provides the software intelligence that matter ...
As businesses evolve, they need technology that is simple to help them succeed today and flexible enough to help them build for tomorrow. Chrome is fit for the workplace of the future — providing a secure, consistent user experience across a range of devices that can be used anywhere. In her session at 21st Cloud Expo, Vidya Nagarajan, a Senior Product Manager at Google, will take a look at various options as to how ChromeOS can be leveraged to interact with people on the devices, and formats th...
SYS-CON Events announced today that Yuasa System will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Yuasa System is introducing a multi-purpose endurance testing system for flexible displays, OLED devices, flexible substrates, flat cables, and films in smartphones, wearables, automobiles, and healthcare.