Skip to main content

EJB best practices: Entity bean protection

Use the Session Facade pattern for safer data management

Brett McLaughlin (brett@newInstance.com), Author and Editor, O'Reilly Media Inc.
Photo of Brett McLaughlin
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

Summary:  How do you enable users to access your application data without directly exposing your entity beans to the Web tier, which could open your application to security threats? Brett McLaughlin offers a solution that is safe for your entity beans and efficient for your overall application.

View more content in this series

Date:  01 Oct 2002
Level:  Intermediate
Activity:  1355 views
Comments:  

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.

Risks of exposure

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.

Exposed beans: A working example

Consider an entity bean called . The bean's methods are getTitle(), getDirector(), and getActors(). Because you've exposed the bean's remote interface, both your application and several client applications have written code that incorporates the getDirector() method. As the application evolves, however, it becomes clear that it should be able to accept movies with multiple directors. The database changes and your getDirector() method becomes getDirectors(). Now the method is plural and coded to return a list, not a single object. As a result, all the code using the old method will break and your application code (as well as your clients' application code) will have to be rewritten.

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.


The Session Facade pattern

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);
      }

A solution to avoid

A common solution to the type of problem described here is to simply add the helper method to the entity bean itself. But the results of doing so can be disastrous. Even if every method in your entity bean changed just once a year, the bean would acquire double the methods by the end of that year. When you consider that methods often change far more rapidly than once a year, it becomes obvious why this "Band-Aid" approach doesn't work. When an entity bean stops looking like a data object and starts looking like a helper class, you know you've got a problem. A session bean, on the other hand, often looks exactly like a helper class, because that's one of the functions session beans are designed to fulfill.

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.


Hiding the data structure

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.


Resources

About the author

Photo of Brett McLaughlin

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

Comments



Trademarks

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Java technology
ArticleID=10710
ArticleTitle=EJB best practices: Entity bean protection
publish-date=10012002
author1-email=brett@newInstance.com
author1-email-cc=