Welcome!

Java IoT Authors: PagerDuty Blog, Pat Romanski, Elizabeth White, Mike Raia, Liz McMillan

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
Internet of @ThingsExpo, taking place November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 19th Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The Internet of Things (IoT) is the most profound change in personal and enterprise IT since the creation of the Worldwide Web more than 20 years ago. All major researchers estimate there will be tens of billions devices - comp...
DevOps at Cloud Expo, taking place Nov 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 19th Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The widespread success of cloud computing is driving the DevOps revolution in enterprise IT. Now as never before, development teams must communicate and collaborate in a dynamic, 24/7/365 environment. There is no time to wait for long dev...
Almost two-thirds of companies either have or soon will have IoT as the backbone of their business in 2016. However, IoT is far more complex than most firms expected. How can you not get trapped in the pitfalls? In his session at @ThingsExpo, Tony Shan, a renowned visionary and thought leader, will introduce a holistic method of IoTification, which is the process of IoTifying the existing technology and business models to adopt and leverage IoT. He will drill down to the components in this fra...
Data is the fuel that drives the machine learning algorithmic engines and ultimately provides the business value. In his session at Cloud Expo, Ed Featherston, a director and senior enterprise architect at Collaborative Consulting, will discuss the key considerations around quality, volume, timeliness, and pedigree that must be dealt with in order to properly fuel that engine.
There is growing need for data-driven applications and the need for digital platforms to build these apps. In his session at 19th Cloud Expo, Muddu Sudhakar, VP and GM of Security & IoT at Splunk, will cover different PaaS solutions and Big Data platforms that are available to build applications. In addition, AI and machine learning are creating new requirements that developers need in the building of next-gen apps. The next-generation digital platforms have some of the past platform needs a...
19th Cloud Expo, taking place November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA, will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud strategy. Meanwhile, 94% of enterpri...
SYS-CON Events announced today Telecom Reseller has been named “Media Sponsor” of SYS-CON's 19th International Cloud Expo, which will take place on November 1–3, 2016, at the Santa Clara Convention Center in Santa Clara, CA. Telecom Reseller reports on Unified Communications, UCaaS, BPaaS for enterprise and SMBs. They report extensively on both customer premises based solutions such as IP-PBX as well as cloud based and hosted platforms.
Pulzze Systems was happy to participate in such a premier event and thankful to be receiving the winning investment and global network support from G-Startup Worldwide. It is an exciting time for Pulzze to showcase the effectiveness of innovative technologies and enable them to make the world smarter and better. The reputable contest is held to identify promising startups around the globe that are assured to change the world through their innovative products and disruptive technologies. There w...
With so much going on in this space you could be forgiven for thinking you were always working with yesterday’s technologies. So much change, so quickly. What do you do if you have to build a solution from the ground up that is expected to live in the field for at least 5-10 years? This is the challenge we faced when we looked to refresh our existing 10-year-old custom hardware stack to measure the fullness of trash cans and compactors.
The emerging Internet of Everything creates tremendous new opportunities for customer engagement and business model innovation. However, enterprises must overcome a number of critical challenges to bring these new solutions to market. In his session at @ThingsExpo, Michael Martin, CTO/CIO at nfrastructure, outlined these key challenges and recommended approaches for overcoming them to achieve speed and agility in the design, development and implementation of Internet of Everything solutions wi...
Cloud computing is being adopted in one form or another by 94% of enterprises today. Tens of billions of new devices are being connected to The Internet of Things. And Big Data is driving this bus. An exponential increase is expected in the amount of information being processed, managed, analyzed, and acted upon by enterprise IT. This amazing is not part of some distant future - it is happening today. One report shows a 650% increase in enterprise data by 2020. Other estimates are even higher....
Today we can collect lots and lots of performance data. We build beautiful dashboards and even have fancy query languages to access and transform the data. Still performance data is a secret language only a couple of people understand. The more business becomes digital the more stakeholders are interested in this data including how it relates to business. Some of these people have never used a monitoring tool before. They have a question on their mind like “How is my application doing” but no id...
The 19th International Cloud Expo has announced that its Call for Papers is open. Cloud Expo, to be held November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA, brings together Cloud Computing, Big Data, Internet of Things, DevOps, Digital Transformation, Microservices and WebRTC to one location. With cloud computing driving a higher percentage of enterprise IT budgets every year, it becomes increasingly important to plant your flag in this fast-expanding business opportuni...
Smart Cities are here to stay, but for their promise to be delivered, the data they produce must not be put in new siloes. In his session at @ThingsExpo, Mathias Herberts, Co-founder and CTO of Cityzen Data, will deep dive into best practices that will ensure a successful smart city journey.
SYS-CON Events announced today that 910Telecom will exhibit at the 19th International Cloud Expo, which will take place on November 1–3, 2016, at the Santa Clara Convention Center in Santa Clara, CA. Housed in the classic Denver Gas & Electric Building, 910 15th St., 910Telecom is a carrier-neutral telecom hotel located in the heart of Denver. Adjacent to CenturyLink, AT&T, and Denver Main, 910Telecom offers connectivity to all major carriers, Internet service providers, Internet backbones and ...
Identity is in everything and customers are looking to their providers to ensure the security of their identities, transactions and data. With the increased reliance on cloud-based services, service providers must build security and trust into their offerings, adding value to customers and improving the user experience. Making identity, security and privacy easy for customers provides a unique advantage over the competition.
I wanted to gather all of my Internet of Things (IOT) blogs into a single blog (that I could later use with my University of San Francisco (USF) Big Data “MBA” course). However as I started to pull these blogs together, I realized that my IOT discussion lacked a vision; it lacked an end point towards which an organization could drive their IOT envisioning, proof of value, app dev, data engineering and data science efforts. And I think that the IOT end point is really quite simple…
Personalization has long been the holy grail of marketing. Simply stated, communicate the most relevant offer to the right person and you will increase sales. To achieve this, you must understand the individual. Consequently, digital marketers developed many ways to gather and leverage customer information to deliver targeted experiences. In his session at @ThingsExpo, Lou Casal, Founder and Principal Consultant at Practicala, discussed how the Internet of Things (IoT) has accelerated our abil...
Is the ongoing quest for agility in the data center forcing you to evaluate how to be a part of infrastructure automation efforts? As organizations evolve toward bimodal IT operations, they are embracing new service delivery models and leveraging virtualization to increase infrastructure agility. Therefore, the network must evolve in parallel to become equally agile. Read this essential piece of Gartner research for recommendations on achieving greater agility.
SYS-CON Events announced today that Venafi, the Immune System for the Internet™ and the leading provider of Next Generation Trust Protection, will exhibit at @DevOpsSummit at 19th International Cloud Expo, which will take place on November 1–3, 2016, at the Santa Clara Convention Center in Santa Clara, CA. Venafi is the Immune System for the Internet™ that protects the foundation of all cybersecurity – cryptographic keys and digital certificates – so they can’t be misused by bad guys in attacks...