Enterprise JavaBeans technology is generally broken down to three core types of beans: session, message-driven, and entity. Beans can also be broken down to those that act as business objects and those that act as data objects. Session beans and message-driven beans are business objects; entity beans are data objects. Most of the time, only business objects need to be exposed to the Web tier (sometimes called the application tier), because business objects can use data objects to deal with data stores. But in some cases, it's necessary to allow users to directly access and manipulate data objects, which means exposing entity beans to the Web tier. This can leave your application open to security threats and can also result in broken code as your application evolves.
In this installment of EJB best practices, we'll discuss why entity beans should never be exposed to the Web tier of an application, and why that can be difficult to avoid. I'll then show you a workaround that is both safer for your entity beans and more efficient for your overall application.
Entity beans reveal a lot about the underlying structure of your database. Because each bean contains accessor and
mutator methods (that is, getxxx() and setxxx()) for every field in the database, and because the method names usually line up with the field names (getFirstName() in the User bean generally accesses the firstName field in the Users table), it's possible to derive an application's entire database structure from its entity beans. While this might not be such a big deal within a single application, your beans are often exposed to other applications on other networks. This is especially true in Web services systems, where applications are linked across multiple networks.
In addition to the obvious dangers of revealing your database structure to unknown applications, you should consider what happens as your data structure changes. Because entity beans are closely tied to your data structure, an entity bean will often change as the columns of a database table change or as new columns are added. By exposing your entity beans to the application layer, you make their method names available, and these method names will almost always be incorporated -- by both your application and outside applications -- into new application code. Severe code snarls can occur as your entity beans change and evolve.
Fortunately, there is a design pattern that will let you enable user access to data objects without exposing your entity beans to the Web tier. The Session Facade pattern places a session bean between the entity bean and application clients. When I use a session bean this way, I like to think of it as a manager, because its role is to manage access to other entities.
Session beans are designed to act as the interface between business logic and application logic. In the case of our working example, the logic is extremely simple, and it only calls out to a single underlying entity bean. In a real-world scenario, however, you might choose to have your session bean manage data validation, security, or any other business-specific functionality. By wrapping your entity beans in session beans, you can access all the business functionality you need to without polluting your entity-bean code.
To resolve the working example, you would create a session bean called MovieManager. The MovieManager bean will contain both the older method, getDirector(), and the new method, getDirectors(). When the new method is added, it is simply "proxied" through to your entity bean. Because the first method is no longer available in the entity bean, the session bean uses a helper method to hide it, as shown in Listing 1:
public Person getDirector() {
// We can't call getDirector() any more on the entity bean
// Call the new method, through this manager
List directors = getDirectors();
// Return the first one in the list
return (Person)directors.item(0);
}
|
Listing 1 isn't a particularly robust adaptation, but it does the trick. Because the old method is hidden (not gone) all the application code that is dependent on it will keep humming along. You've also kept the helper method out of the entity bean by placing it in your business objects where it belongs. With the immediate problem resolved, you have the option to manually migrate your bean's clients to the new method or let the helper method handle the migration indefinitely. Either way, neither your application code nor your clients' code will suffer.
While the above solution does resolve the issue of change management, it doesn't do away with your security concerns. You still need to protect your entity beans (and thus your data structure) from exposure to the Web tier. By adding some simple business logic and data manipulation functionality to your session bean, you can both hide your application's data structure and provide more sophisticated access to the information it contains.
For example, as your application evolves you might find it inefficient to let users access various data objects (for example, directors, producers, actors) one by one. Because this type of information is almost always pulled and used together, you might find it useful to repurpose your session bean. Rather than a getDirector() or getDirectors() method, your session bean could contain the new business logic shown in Listing 2:
public List getCrew(String movieName)
throws NamingException, RemoteException {
List crew = new LinkedList();
EJBHomeFactory f = EJBHomeFactory.getInstance();
MovieHome movieHome =
(MovieHome)f.lookup("java:comp/env/ejb/Movie", MovieHome.class);
Movie movie = movieHome.findByName(movieName);
crew.add(movie.getDirectors());
crew.add(movie.getProducers());
crew.add(movie.getExecutiveProducers());
// and so on...
return crew;
}
public List getCast(String movieName)
throws NamingException, RemoteException {
List cast = new LinkedList();
EJBHomeFactory f = EJBHomeFactory.getInstance();
MovieHome movieHome =
(MovieHome)f.lookup("java:comp/env/ejb/Movie", MovieHome.class);
Movie movie = movieHome.findByName(movieName);
crew.add(movie.getActors());
crew.add(movie.getStandIns());
// and so on...
return cast;
}
|
By separating different application tiers and using business logic to handle data manipulation, you've simultaneously prevented direct, and possibly insecure, access to your entity beans and created a more meaningful set of methods for your Web tier. In this case, the Session Facade acts as both a wrapper for your entity bean and a true business-logic unit, turning raw data into meaningful information.
The Session Facade pattern is the basic building block for many other design patterns, and its advantages go well beyond those discussed here. In the next installment of EJB best practices, we'll use the Business Interface pattern we examined in the first tip in this series, along with some of the tricks you've learned here, to further abstract the process of using all types of EJB components in your applications.
- In his article "Best practices in EJB exception handling" (developerWorks, May 2002), Java architect Srikanth Shenoy demonstrates how to code for faster problem resolution on EJB technology-based systems.
- Sun Microsystems EJB technology home page is a good starting place for information on EJB technology.
- Another great resource, TheServerSide.com, offers articles and information pertaining to J2EE.
- See the developerWorks Java zone tutorials page for a listing of free EJB technology- and J2EE-related tutorials.
- Find hundreds more Java technology resources on the developerWorks Java technology zone.

Brett McLaughlin has been working in computers since the Logo days (remember the little triangle?). He currently specializes in building application infrastructure using Java and Java-related technologies. He has spent the last several years implementing these infrastructures at Nextel Communications and Allegiance Telecom, Inc. Brett is one of the co-founders of the Java Apache project, Turbine, which builds a reusable component architecture for Web application development using Java servlets. He is also a contributor of the EJBoss project, an open source EJB application server, and Cocoon, an open source XML Web-publishing engine. Contact Brett at brett@oreilly.com