Welcome!

Java Authors: Elizabeth White, Carmen Gonzalez, Lori MacVittie, Trevor Parsons, Peter Silva

Related Topics: Java, Websphere

Java: Article

Cover Story: What Is POJO Programming?

Introducing POJO application development

The novel A Deepness in the Sky by Vernor Vinge is set in the distant future. The character Pham Nuwen is responsible for maintaining software whose components are thousands of years old. Today, however, it's difficult to imagine maintaining an Enterprise Java application for more than a few years. More often than not, the application is tightly coupled to infrastructure frameworks that evolve rapidly in ways that don't preserve backwards compatibility. Consequently, upgrading to a new and improved framework can be challenging and risky.

Fortunately, there's now a much better way to build Enterprise Java applications: Plain Old Java Objects (POJOs), which are classes that don't implement infrastructure framework-specific interfaces, and non-invasive frameworks such as Spring, Hibernate, JDO, and EJB 3, which provide services for POJOs.

Using POJOs future proofs your application's business logic by decoupling it from volatile, constantly evolving infrastructure frameworks. Upgrading to a new version or switching to a different framework becomes easier and less risky. POJOs also make testing easier, which simplifies and accelerates development. Your business logic will be clearer and simpler because it won't be tangled with the infrastructure code. And, as an added bonus, you can often deploy a POJO application using a simpler, Web container-only application server.

In this article, you'll learn about POJO programming. I'll begin by describing the concept of POJOs. You'll then get an overview of persisting POJOs with Hibernate and EJB 3 and making them transactional with EJB 3 and Spring. Of course, it's unlikely that the applications we're developing today will be used thousands of years from now but until their demise, using POJOs will make it easier to upgrade them to use newer frameworks.

What Is a POJO?
Even though it has tremendous benefits, the concept of a POJO is remarkably simple. A POJO is a Java object that doesn't implement any special interfaces such as those defined by the EJB 2 framework. Martin Fowler, Rebbecca Parsons, and Josh MacKenzie coined the name to give regular Java objects an exciting-sounding name that encouraged developers to use them (www.martinfowler.com/bliki/POJO.html).

To contrast the EJB and POJO approaches consider the following example. Imagine that you worked for a bank and needed to implement a service to transfer money from one bank account to another. If you were using EJB2, your code would most likely consist of a MoneyTransferService stateless session bean that coordinated the transfer of money between the accounts and an Account entity bean that accessed the account data. The problem with this design is that each EJB would be a mixture of business logic and EJB 2 infrastructure code. They would be intimately coupled to the EJB 2 framework. Furthermore, they would be difficult to test without deploying unless you jumped through the kinds of hoops described in TwoLevelDomain (www.theserverside.com/articles/article.tss?l=TwoLevelDomainModel).

By comparison, the POJO version (which is downloadable from www.pojosinaction.com) would look something like Listing 1. The MoneyTransferService and its implementation class define a transfer() method and the Account class maintains a balance and defines debit() and credit() methods. The AccountDAO is the interface for the Data Access Object (DAO) class whose implementation I'll describe later.

As you can see, these are regular Java classes. None of them implement special interfaces or call any framework classes. What's more, the MoneyTransferService doesn't instantiate the AccountDAO directly or look it up using an API such as JNDI. Instead, the AccountDAO is passed as a constructor parameter. This is an example of what is termed dependency injection, which is one of the key enablers for POJO development (www.martinfowler.com/articles/injection.html). In this example, dependency injection decouples the MoneyTransferService from the infrastructure framework. The MoneyTransferService only depends on the AccountDAO interface - not on the framework used to implement the AccountDAO or an API such as JNDI.

You could, of course, simplify the MoneyTransferService by dispensing with the AccountDAO and directly injecting, for example, a Spring HibernateTemplate or an EJB 3 EntityManager. However, I generally prefer to keep my framework-specific data access code separate from my business logic.

The Benefits of POJOs
Decoupling the application code from the infrastructure frameworks is one of the many benefits of using POJOs. They also simplify development because rather than being forced to think about everything - business logic, persistence, transactions, etc. - at once, you can focus instead on one thing at a time. You can design and implement the business logic and then, once that's working, you can deal with persistence and transactions.

POJOs also accelerate development. You can test your business logic outside of the application server and without a database. You don't have to package your code and deploy it in the application server. You also don't have to keep the database schema constantly in sync with the object model or spend time waiting for slow-running database tests to finish. Tests run in a few seconds and development can happen at the speed of thought - or at least as fast as you can type!

But by now you probably have questions such as what about transactions? Security? Persistence? Remoting? And how do you assemble an application with dependency injection? As you might have guessed, POJOs by themselves are insufficient. To use them in an enterprise application you have to use one or more frameworks.

Overview of Frameworks for POJOs
When developing an enterprise application, you need services such as transaction management, security, and persistence. You also need a way to assemble components together and access enterprise resources such as JDBC DataSources. One option is to use some very popular non-EJB frameworks such as Hibernate, JDO, and Spring. The Hibernate and JDO frameworks provide persistence for POJOs. The Spring framework provides services for POJOs such as transaction management and dependency injection. It also has support for POJO remoting and is the foundation of the Acegi Security framework (http://acegisecurity.sourceforge.net) that provides security for POJOs. One big of advantage of not using the EJB container is that you can sometimes deploy your POJO application in a simple (and sometimes cheaper) Web container-only server.

Another option is to use the emerging EJB 3 standard, which has adopted many POJO concepts and is a big improvement over EJB 2. In EJB 3, EJBs are very POJO-like in not implementing any special interfaces. Furthermore, EJB 3 entity beans are intended to be the standard persistence mechanism for Java and work both inside and outside the EJB container.

One important benefit of EJB 3, Spring, Hibernate, and JDO is that they are non-invasive. Unlike older technologies such as EJB2, they provide services such as transactions and persistence without requiring the application classes to implement any special interfaces. Moreover, only a small fraction of your code must call any APIs. Classes can be transactional or persistent while still being POJOs.

To use the services provided by these frameworks you must write metadata that configures the frameworks. The metadata comes in the form of either Java 5 annotations or XML configuration files. Later in this article, I'll provide examples of how you use this metadata to map POJOs to a relational database and make them transactions.

Now that you have had an overview of POJOs and their associated frameworks, let's look at dependency injection, persistence, and transaction management in more detail.

Injecting Dependencies into POJOs
Earlier we saw how the AccountDAO was passed as a constructor parameter to the MoneyTransferService. This kind of dependency injection is called constructor injection. Another kind of dependency injection is setter injection and consists of passing dependencies as setter parameters. The third kind of dependency injection is field injection and involves initializing fields directly. I prefer to use constructor injection because it ensures that an object is constructed with the required dependencies but setter and field injection are also useful.

Dependency injection has the following benefits:

  • Simpler code - It eliminates the need to call lookup APIs. Because a component's dependencies are passed to it you no longer have to write tedious JNDI code to look up a dependency.
  • Decouples application components from one another and the infrastructure framework - Dependency injection lets you construct an application from loosely coupled components. Components depend mainly on interfaces rather than on concrete implementations. There are no calls to framework-specific lookup code. The dependencies on the infrastructure frameworks are localized to only those components that call them directly such as DAO implementations.
  • Easier testing - You can test components in isolation by injecting mock implementations. For example, we can write tests for the MoneyTransferService that use a mock implementation of the AccountDAO. These kinds of tests are essential if you want to be able to work on your business logic without worrying about persistence. They also run a lot faster than those that access a database.
There has to be some application start-up code that instantiates the components and wires them together. You could write the start-up code yourself. For example, you could write some code that creates an instance of a class that implements AccountDAO and then passes it to an instance of the MoneyTransferServiceImpl. However, in a typical application it's usually more convenient to let Spring or EJB 3 inject the dependencies for you.

Spring Dependency Injection
Dependency injection is one of the core features of the Spring framework. To use it, you must configure Spring's bean factory, which is a sophisticated factory that instantiates objects and wires them together using either constructor injection or setter injection. Here's an example of how to do that:

<bean name="moneyTransferService" class="... MoneyTransferServiceImpl">
    <constructor-arg ref="accountDAO"/>
</bean>

<bean name="accountDAO" class="... AccountDAOHibernateImpl">
...
</bean>

More Stories By Christopher Richardson

Chris Richardson is the author of the recently published POJOs in Action. He's a developer, architect, and mentor with over 20 years of experience. Chris runs a consulting company that jumpstarts new development projects and helps teams that are frustrated with Enterprise Java to become more productive and successful. He lives in Oakland, CA with his wife and three children.

Comments (8) 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
Preet 06/24/08 01:42:08 PM EDT

interesting read... answers the what, but, and what ifs..
Thanks! I am newbie in this domain and this is exactly what I was looking for.

Mathan 02/26/08 10:39:21 AM EST

The main advantage of the POJOs are felt in distributed applications. Assume that your application is consuming services from 10 different applications. If one of them is down, then your application is effectively down. Instead, if you have the POJOs for all those apps bundled in your app, then your application can stand alone without any dependency

rogerv 03/28/06 05:20:31 PM EST

What Is POJO Programming?

Oh - that's where you write 30% of a Java application in a declarative, XML-based domain specific language.

For all practical purposes (and by very definition) the domain specific language will be unique to a given POJO container and hence will render the Java application essentially unportable.

Patrick Ellul 03/14/06 10:25:04 PM EST

I found this article very helpful with introducing me to the concepts behind POJO's and ORM's and frameworks such as Spring and Hibernate.

Justin Peck 03/13/06 12:28:09 AM EST

I liked this article so much, I wrote a Web application after having read it. Spring really does make programming Java-base Web apps fun again. Thanks for the article!

[You can see the app now at http://javajuster.com]

Alain Ah Ming 02/26/06 05:21:30 AM EST

Is this simply replacing the underlying entity EJB with the value object?
If a J2EE app were designed in a way that we had distinct segregation as follows:
Session EJB --> BusinessLogic Helper class --ValueObj--> DAO interface --ValueObj--> DAO impl class --ValueObj--> Entity EJB

would that would make it as good as what POJO prog is trying to achieve?

From our test class, we can easily invoke our business logic helper class (which is a pure POJO) by injecting a test DAO impl class.
That effectively leaves out any dependency to the underlying framework (EJB or spring).

harris reynolds 02/23/06 05:39:06 PM EST

Trackback Added: JDJ RIP; I receive several trade rags about technolgy. Most of them get stacked up in a pile by my desk that I eventually go through after they start cluttering the office. When going through the latest round of magazines recently I...

SYS-CON Italy News Desk 02/21/06 01:40:28 PM EST

The novel A Deepness in the Sky by Vernor Vinge is set in the distant future. The character Pham Nuwen is responsible for maintaining software whose components are thousands of years old. Today, however, it's difficult to imagine maintaining an Enterprise Java application for more than a few years. More often than not, the application is tightly coupled to infrastructure frameworks that evolve rapidly in ways that don't preserve backwards compatibility. Consequently, upgrading to a new and improved framework can be challenging and risky.

@ThingsExpo Stories
Whether you're a startup or a 100 year old enterprise, the Internet of Things offers a variety of new capabilities for your business. IoT style solutions can help you get closer your customers, launch new product lines and take over an industry. Some companies are dipping their toes in, but many have already taken the plunge, all while dramatic new capabilities continue to emerge. In his session at Internet of @ThingsExpo, Reid Carlberg, Senior Director, Developer Evangelism at salesforce.com, to discuss real-world use cases, patterns and opportunities you can harness today.
The Internet of Things (IoT) is going to require a new way of thinking and of developing software for speed, security and innovation. This requires IT leaders to balance business as usual while anticipating for the next market and technology trends. Cloud provides the right IT asset portfolio to help today’s IT leaders manage the old and prepare for the new. Today the cloud conversation is evolving from private and public to hybrid. This session will provide use cases and insights to reinforce the value of the network in helping organizations to maximize their company’s cloud experience.
Cultural, regulatory, environmental, political and economic (CREPE) conditions over the past decade are creating cross-industry solution spaces that require processes and technologies from both the Internet of Things (IoT), and Data Management and Analytics (DMA). These solution spaces are evolving into Sensor Analytics Ecosystems (SAE) that represent significant new opportunities for organizations of all types. Public Utilities throughout the world, providing electricity, natural gas and water, are pursuing SmartGrid initiatives that represent one of the more mature examples of SAE. We have spoken with, or attended presentations from, utilities in the United States, South America, Asia and Europe. This session will provide a look at the CREPE drivers for SmartGrids and the solution spaces used by SmartGrids today and planned for the near future. All organizations can learn from SmartGrid’s use of Predictive Maintenance, Demand Prediction, Cloud, Big Data and Customer-facing Dashboards...
IoT is still a vague buzzword for many people. In his session at Internet of @ThingsExpo, Mike Kavis, Vice President & Principal Cloud Architect at Cloud Technology Partners, will discuss the business value of IoT that goes far beyond the general public's perception that IoT is all about wearables and home consumer services. The presentation will also discuss how IoT is perceived by investors and how venture capitalist access this space. Other topics to discuss are barriers to success, what is new, what is old, and what the future may hold.
All major researchers estimate there will be tens of billions devices – computers, smartphones, tablets, and sensors – connected to the Internet by 2020. This number will continue to grow at a rapid pace for the next several decades. With major technology companies and startups seriously embracing IoT strategies, now is the perfect time to attend @ThingsExpo in Silicon Valley. Learn what is going on, contribute to the discussions, and ensure that your enterprise is as "IoT-Ready" as it can be!
Noted IoT expert and researcher Joseph di Paolantonio (pictured below) has joined the @ThingsExpo faculty. Joseph, who describes himself as an “Independent Thinker” from DataArchon, will speak on the topic of “Smart Grids & Managing Big Utilities.” Over his career, Joseph di Paolantonio has worked in the energy, renewables, aerospace, telecommunications, and information technology industries. His expertise is in data analysis, system engineering, Bayesian statistics, data warehouses, business intelligence, data mining, predictive methods, and very large databases (VLDB). Prior to DataArchon, he served as a VP and Principal Analyst with Constellation Group. He is a member of the Boulder (Colo.) Brain Trust, an organization with a mission “to benefit the Business Intelligence and data management industry by providing pro bono exchange of information between vendors and independent analysts on new trends and technologies and to provide vendors with constructive feedback on their of...
Software AG helps organizations transform into Digital Enterprises, so they can differentiate from competitors and better engage customers, partners and employees. Using the Software AG Suite, companies can close the gap between business and IT to create digital systems of differentiation that drive front-line agility. We offer four on-ramps to the Digital Enterprise: alignment through collaborative process analysis; transformation through portfolio management; agility through process automation and integration; and visibility through intelligent business operations and big data.
There will be 50 billion Internet connected devices by 2020. Today, every manufacturer has a propriety protocol and an app. How do we securely integrate these "things" into our lives and businesses in a way that we can easily control and manage? Even better, how do we integrate these "things" so that they control and manage each other so our lives become more convenient or our businesses become more profitable and/or safe? We have heard that the best interface is no interface. In his session at Internet of @ThingsExpo, Chris Matthieu, Co-Founder & CTO at Octoblu, Inc., will discuss how these devices generate enough data to learn our behaviors and simplify/improve our lives. What if we could connect everything to everything? I'm not only talking about connecting things to things but also systems, cloud services, and people. Add in a little machine learning and artificial intelligence and now we have something interesting...
Last week, while in San Francisco, I used the Uber app and service four times. All four experiences were great, although one of the drivers stopped for 30 seconds and then left as I was walking up to the car. He must have realized I was a blogger. None the less, the next car was just a minute away and I suffered no pain. In this article, my colleague, Ved Sen, Global Head, Advisory Services Social, Mobile and Sensors at Cognizant shares his experiences and insights.
We are reaching the end of the beginning with WebRTC and real systems using this technology have begun to appear. One challenge that faces every WebRTC deployment (in some form or another) is identity management. For example, if you have an existing service – possibly built on a variety of different PaaS/SaaS offerings – and you want to add real-time communications you are faced with a challenge relating to user management, authentication, authorization, and validation. Service providers will want to use their existing identities, but these will have credentials already that are (hopefully) irreversibly encoded. In his session at Internet of @ThingsExpo, Peter Dunkley, Technical Director at Acision, will look at how this identity problem can be solved and discuss ways to use existing web identities for real-time communication.
Can call centers hang up the phones for good? Intuitive Solutions did. WebRTC enabled this contact center provider to eliminate antiquated telephony and desktop phone infrastructure with a pure web-based solution, allowing them to expand beyond brick-and-mortar confines to a home-based agent model. It also ensured scalability and better service for customers, including MUY! Companies, one of the country's largest franchise restaurant companies with 232 Pizza Hut locations. This is one example of WebRTC adoption today, but the potential is limitless when powered by IoT. Attendees will learn real-world benefits of WebRTC and explore future possibilities, as WebRTC and IoT intersect to improve customer service.
From telemedicine to smart cars, digital homes and industrial monitoring, the explosive growth of IoT has created exciting new business opportunities for real time calls and messaging. In his session at Internet of @ThingsExpo, Ivelin Ivanov, CEO and Co-Founder of Telestax, will share some of the new revenue sources that IoT created for Restcomm – the open source telephony platform from Telestax. Ivelin Ivanov is a technology entrepreneur who founded Mobicents, an Open Source VoIP Platform, to help create, deploy, and manage applications integrating voice, video and data. He is the co-founder of TeleStax, an Open Source Cloud Communications company that helps the shift from legacy IN/SS7 telco networks to IP-based cloud comms. An early investor in multiple start-ups, he still finds time to code for his companies and contribute to open source projects.
The Internet of Things (IoT) promises to create new business models as significant as those that were inspired by the Internet and the smartphone 20 and 10 years ago. What business, social and practical implications will this phenomenon bring? That's the subject of "Monetizing the Internet of Things: Perspectives from the Front Lines," an e-book released today and available free of charge from Aria Systems, the leading innovator in recurring revenue management.
The Internet of Things will put IT to its ultimate test by creating infinite new opportunities to digitize products and services, generate and analyze new data to improve customer satisfaction, and discover new ways to gain a competitive advantage across nearly every industry. In order to help corporate business units to capitalize on the rapidly evolving IoT opportunities, IT must stand up to a new set of challenges.
There’s Big Data, then there’s really Big Data from the Internet of Things. IoT is evolving to include many data possibilities like new types of event, log and network data. The volumes are enormous, generating tens of billions of logs per day, which raise data challenges. Early IoT deployments are relying heavily on both the cloud and managed service providers to navigate these challenges. In her session at 6th Big Data Expo®, Hannah Smalltree, Director at Treasure Data, to discuss how IoT, Big Data and deployments are processing massive data volumes from wearables, utilities and other machines.
P2P RTC will impact the landscape of communications, shifting from traditional telephony style communications models to OTT (Over-The-Top) cloud assisted & PaaS (Platform as a Service) communication services. The P2P shift will impact many areas of our lives, from mobile communication, human interactive web services, RTC and telephony infrastructure, user federation, security and privacy implications, business costs, and scalability. In his session at Internet of @ThingsExpo, Erik Lagerway, Co-founder of Hookflash, will walk through the shifting landscape of traditional telephone and voice services to the modern P2P RTC era of OTT cloud assisted services.
While great strides have been made relative to the video aspects of remote collaboration, audio technology has basically stagnated. Typically all audio is mixed to a single monaural stream and emanates from a single point, such as a speakerphone or a speaker associated with a video monitor. This leads to confusion and lack of understanding among participants especially regarding who is actually speaking. Spatial teleconferencing introduces the concept of acoustic spatial separation between conference participants in three dimensional space. This has been shown to significantly improve comprehension and conference efficiency.
The Internet of Things is tied together with a thin strand that is known as time. Coincidentally, at the core of nearly all data analytics is a timestamp. When working with time series data there are a few core principles that everyone should consider, especially across datasets where time is the common boundary. In his session at Internet of @ThingsExpo, Jim Scott, Director of Enterprise Strategy & Architecture at MapR Technologies, will discuss single-value, geo-spatial, and log time series data. By focusing on enterprise applications and the data center, he will use OpenTSDB as an example to explain some of these concepts including when to use different storage models.
SYS-CON Events announced today that Gridstore™, the leader in software-defined storage (SDS) purpose-built for Windows Servers and Hyper-V, will exhibit at SYS-CON's 15th International Cloud Expo®, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Gridstore™ is the leader in software-defined storage purpose built for virtualization that is designed to accelerate applications in virtualized environments. Using its patented Server-Side Virtual Controller™ Technology (SVCT) to eliminate the I/O blender effect and accelerate applications Gridstore delivers vmOptimized™ Storage that self-optimizes to each application or VM across both virtual and physical environments. Leveraging a grid architecture, Gridstore delivers the first end-to-end storage QoS to ensure the most important App or VM performance is never compromised. The storage grid, that uses Gridstore’s performance optimized nodes or capacity optimized nodes, starts with as few a...
The Transparent Cloud-computing Consortium (abbreviation: T-Cloud Consortium) will conduct research activities into changes in the computing model as a result of collaboration between "device" and "cloud" and the creation of new value and markets through organic data processing High speed and high quality networks, and dramatic improvements in computer processing capabilities, have greatly changed the nature of applications and made the storing and processing of data on the network commonplace. These technological reforms have not only changed computers and smartphones, but are also changing the data processing model for all information devices. In particular, in the area known as M2M (Machine-To-Machine), there are great expectations that information with a new type of value can be produced using a variety of devices and sensors saving/sharing data via the network and through large-scale cloud-type data processing. This consortium believes that attaching a huge number of devic...