BUY THIS BOOK
Add to Cart

Print Book $39.95


Safari Books Online

What is this?

Add to UK Cart

Print Book £28.50

What is this?

Looking to Reprint this content?


Building Java Enterprise Applications
Building Java Enterprise Applications

By Brett McLaughlin
Price: $39.95 USD
£28.50 GBP

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: Introduction
Java has become a confusing world. Five years ago, there were few decisions to make once you started programming in Java—you used AWT for graphical user interfaces, sockets for network programming, and hacked together everything else you needed. Since then, though, the APIs available for the Java language have grown, and grown. . . and grown. Now you can dabble in Swing, servlets, Enterprise JavaBeans (EJB), JavaMail, and more. Additionally, there are now packages of APIs, like the Java 2 Micro Edition (J2ME) and Java 2 Enterprise Edition (J2EE). While these packages seem to be nicely wrapped bundles of useful APIs, they don't help the average developer figure out how to piece together the APIs contained in these packages. Though it's simple to find documentation on the individual APIs, getting the "big picture" is difficult, at best. One of the most interesting, but difficult, aspects of Java today is building Java enterprise applications using the J2EE package.
All of this has led the folks at O'Reilly to be interested in a book specifically focused on building enterprise applications with these APIs. Instead of small, piecemeal examples, we've found that readers want large applications built from the ground up, and explanations of design decisions. Additionally, readers have been adamant about seeing more than just the Java part of the picture; they want to know how to set up a database, and get an LDAP store running, and integrate these. How does a UDDI registry fit into the equation? I'm going to address all of these issues in this series (yes, I said series!) of books, Building Java Enterprise Applications. You hold Volume I in your hands.
So, this chapter is a true introduction. Not only will it introduce you to what I'll be covering in this book and the materials you'll need to follow along, but it will also tell you how this series is going to be put together. You'll see what's coming in Volumes II and III, how the examples are structured, and what topics will be covered in this book as well as future ones.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Building Java Enterprise Applications
From the first page of the first chapter to the last page of the last index, this series is going to focus on building applications. That probably sounds redundant, since you picked up this book knowing the title, but let me explain what I mean. First, I'm not going to explain the basics of the technologies used in this book. If you don't know what an entity bean is, or haven't ever written a SQL statement, or want to learn about JSPs, this book isn't for you. I'd recommend you pick up a copy of the O'Reilly book on the subject you want to learn about, and start there. Section 1.3.3 at the end of this chapter is a good reference for linking a subject to the right O'Reilly book.
Second, this book is aimed squarely at the enterprise developer, and especially at someone who has an existing or upcoming project that uses all or part of the J2EE platform. I'll explain later what constitutes an enterprise application, but this book will be most helpful if you have some real business problems to solve and can apply the concepts in these chapters directly to them.
Third, I expect you to be comfortable with (and hopefully, desirous of) lots of code. I'm going to try to keep explanations to the bare minimum on basic concepts, and instead focus on tougher problems, real-world issues that aren't covered in other books, and typical mistakes I see in day-to-day programming. If you're not ready to wade through a lot of code (thousands of lines in this volume, for starters), you might want to set this down and pick it up again once you've had a little more experience (as if any real programmer would put something down because it's over their head!).
Fourth, this book focuses on writing applications from the ground up, using only Java as the programming language. While many enterprise applications do have to deal with legacy code or non-Java system integration, that is a topic well unto itself. To keep things clear and concise, this book deals with systems that are entirely based on the Java programming language. While the third volume on web services will certainly touch on integration with other languages, this architecture volume does not.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Architecture
Now that you have a good idea of how the volumes in this series progress, I want to focus on what will be covered in this book. This description follows the flow of the book itself, and lets you know where to turn if you're looking for something specific. I'll also give you a little more detail here than what is in the the preface.
After walking through some design issues, the first technical topic in this book is that of databases. Although almost every Java developer working on enterprise applications has used a database, very few are competent database developers. In other words, programmers know how to create rows and columns, but have very little understanding of the best way to tune tables, of how to perform database normalization, or of making a database work in an efficient, useful way.
In the chapters on database design and setup, I'll show how to create a database structure via the Structured Query Language (SQL). More importantly, I'll focus on how to set up a good relational structure and examine how EJBs need to access the data. This discussion should allow you to move from using a database to mastering one, at least in the context of enterprise applications. Discussions will be applicable to any database vendor.
While traditional relational databases are still the prevalent force for data storage in enterprise applications, alternative data mediums are becoming popular. XML-based databases and object-oriented databases are in direct competition with relational databases, and directory servers offer a complementary solution to existing databases. For data that is read far more often than it is written, directory servers excel in performance. Examples of this sort of data are authentication credentials, such as usernames and passwords, which tend to be performance-driven. In other words, the less time a user waits to log in, the better your application is perceived.
This book takes an extensive look at directory servers in order to show you how to develop systems that integrate multiple types of data stores. I'll explain how to set up the directory store schema (which is analogous to the tables and columns of a relational database) and how to populate the directory store. I'll also show you how the Java Naming and Directory Interface (JNDI) can provide fast access to a directory server. Finally, I'll cover the tricky issues that surround using multiple data stores: replication, data overlap, and keeping data in sync and uncorrupted.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
What You'll Need
Before getting into the thick of things, let's take a moment to cover what you'll need to work through this book. Most crucial are the APIs involved, but also important are the application server, the tools I'll refer to, and all the support facilities for writing enterprise applications. You'll also probably have your own set of tools (code editors, HTML editors, etc.), and you should not have too much trouble adapting to any of the instructions for specific products that you use.
First and foremost, this book is focused on the 1.3 version of the J2EE specification. You can download the J2EE specification from Sun online at http://java.sun.com/j2ee. I also highly recommend that you download the J2EE SDK (essentially the reference implementation), which can be used for running the example code.
Let me say a word about application servers. There are as many application server vendors as there are colors, and picking one isn't always a trivial task. Additionally, trying to cover the nuances of each application server in a single book is simply impossible; you'll always find a vendor or version that doesn't fit the instructions, and in those cases a book's instructions can cause confusion instead of resolving it. To keep this to a minimum, I've taken two steps. First, the content in the chapters of this book is focused on APIs, code, and deployment descriptors, and will work on any J2EE 1.3 application server. In other words, the chapters are all vendor-neutral. However, this leaves a lot of vendor-specific detail up in the air, as most application servers have specific instructions for setup and deployment. To accommodate this, the appendixes in this book will show you how to get the examples to work using the BEA Weblogic application server.
If you work in an environment where another application server is in use, you can take your applications and deploy them to that application server, using the specific vendor's documentation. The result is an application that is as portable as it can be in today's world of too-many variations on the J2EE theme. Additionally, as demand and time dictate, instructions for working with other popular application servers will be posted online at this book's web site,
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Blueprints
Let's begin to delve into enterprise applications. With some basic knowledge of the Java APIs and related technologies (such as XML) that are involved with these applications, you are as qualified as the next programmer to start building applications! This is a new frontier, even though it's been three or four years since the J2EE specification was released. That may sound a bit far-fetched, but technology is moving at an incredible rate, as are the APIs that support it. Just two years ago, applications had far fewer tools, technologies, and specifications upon which to build. For these reasons, you start with most other programmers on a generally level playing field. And as each phase of building an application is addressed, I discuss the principles that will guide you in your own applications, using any combination of APIs and tools.
However, discussing these complex applications in the abstract is like talking about music (which is like dancing about architecture, according to Miles Davis). In other words, trying to describe how to build an application without in fact building one is nearly impossible. For that reason, this entire series discusses the Java APIs and code within the context of a large, enterprise application that will be accessible through a web interface (in Volume II) and as a web service (in Volume III). Starting in this chapter, I will detail a fictional company, Forethought Brokerage, and discuss the application they are building (or rather, that you are building for them). Beginning with only a set of requirements, you will construct the Forethought application from the ground up, including data storage, API selection, and of course implementation. At the end of the series, the application will finally be ready to run, complete with several advanced features that are usable in your own applications. In this first volume, you'll build a data store that includes a database, a directory server, and numerous Enterprise JavaBeans.
This chapter begins the process by presenting a set of requirements. I will take these requirements and design blueprints for the application, "roughing out" each portion of the application and explaining each decision made. With this set of blueprints in hand, it's possible to detail each section of the application. Additionally, in a commercial environment, multiple teams could work on different portions of the application in parallel; this is possible only with a well-designed set of plans for the application, agreed upon before development begins. Although you are the only developer working on the example application, following this practice will teach you how to design your own applications so that multiple programmers can work on them. Once a general set of requirements is laid out and met, I'll run through a brief survey of the key technologies used throughout the rest of this book. If you are familiar with databases, directory servers, enterprise Java, and XML, you can probably skim these later sections of the chapter. However, if you're new to enterprise programming, these descriptions will help prepare you for the chapters that follow.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Forethought Brokerage
Like any good building, an application begins with a set of requirements, often having little to do with implementation details. The first challenge of constructing an application, then, is to translate these requirements into technological outlines and a plan for action. While this can be simple when the person or group defining these requirements is technical, it is far more often the case that this mapping of requirements to an application blueprint is the most difficult portion of architecting an application. A marketing or product management group explaining their needs rarely has an idea of what is technically feasible, or even possible, with today's programming languages. Additionally, these initial requirements have a way of changing during a project, resulting in a moving target for completing a "successful" application. In fact, this is the first lesson in building an application: an application that meets the initial set of requirements is not automatically a success! Instead, it must anticipate the changing of requirements and be able to adapt in kind. For this reason, a flexible architecture and well-designed set of blueprints can lead to customer sign-off, protecting the application designer from these changes, or at least providing a reasonable window of change when requirements do evolve. This is the kind of architecture and blueprint that must be developed for Forethought Brokerage.
Forethought Brokerage has been serving their clients in a traditional investment brokerage sense for nearly 20 years. Specializing in long-term clients and customer service, the brokerage has until recently run their entire operation largely through a paper office, using carbon receipts, conference calls, and face-to-face meetings. They have monitored their clients' funds through frequent phone calls, monitoring the market, and by sweat and hard work. Although this has succeeded in building their client base and keeping them in business for almost 20 years, it has also caused some problems. They have had to remain a locally based business, as they have no facility to handle clients around the country and the world, and their established pattern of personal consultations begins to break down over distance. Additionally, monitoring funds in 24 time zones instead of one is a significant increase in workload.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Data Layer
The foundation of any application is the data that it contains and utilizes. Without data, there is no need for an application! Unfortunately, designing a data layer does not produce immediate visible results—no screens appear, no business logic occurs, and management is rarely impressed with entity-relationship diagrams. Because of this, the data layer is often designed and implemented hastily, leaving the rest of the application to suffer and compensate for early mistakes. Instead of taking this precarious approach, this book covers the data layer first and attempts to design it soundly.
In addition to data storage, data access is typically part of the data layer. However, these different functions can be separated from each other; do not be tempted to model your data differently because of a product or technique used in the data access layer. More often than not, the data of an application outlasts the application itself. Data formatted for a specific product or application server may be completely unusable for other products that expect data in a standard format. Only after the data has been modeled and the storage mediums designed should data access be considered. This section covers databases and directory servers as well as data access methods.
Once you decide to use a relational database, the number of decisions left decreases quite a bit. First, you must choose a database vendor. Second, the database must be accessible through a JDBC (Java Database Connectivity) driver. Then, the data design must be determined, and finally, the data schema should be populated.
Determining what database to use can be very difficult; the data of an application often outlasts other parts of an application, or becomes used by other applications, over time. This means that your database vendor (and your resulting relationship with the vendor) will play a critical role. Often, though, this decision is taken out of the developer's hands; many large companies establish a standard vendor and simply purchase new licenses for additional database instances as needed. In these cases, you will simply need to become familiar with the selected vendor. However, in the case where no standard exists, there are numerous options. Trying to recommend a single option for all cases is impossible; instead, certain conditions favor specific vendors. On large systems, and particularly on Sun Solaris hardware, Oracle is an excellent choice. Linux servers and clusters often use Oracle as well, and open source solutions like MySQL, PostgreSQL, and InstantDB are also popular. Microsoft platforms tend to work best with the Microsoft database offering, MS SQL Server. And there are many, many other vendors to choose from, such as Sybase, Cloudscape, mSQL, and Interbase. While the example code shown in this book utilizes only standard ANSI SQL and should work on any of these databases, the appendixes cover various database-specific SQL idioms.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Business Layer
Next in the design process is the task of creating a business layer. This portion of the application is wedged between presentation (what the user sees) and data (what the application depends on). The business layer, then, does just what it implies: it performs business (logic). Data on its own is rarely relevant, and often makes no sense without some context applied to it. In the same fashion, the presentation layer must have something to present (no rocket science here!). In this business layer, then, data is manipulated, transformed, and converted into content suitable for presentation.
The core of this layer is the code that actually executes business logic. This code maps to a company's business processes; in the best case, a single module of code represents a single business process. These modules can then be called to obtain a client's outstanding balance, for example. This figure is rarely stored in the database, but instead is calculated from the client's purchases subtracted from his or her assets. This allows the raw data to be masked from the presentation layer of an application; instead of asking for data and performing calculations, the application needs to request only the business process that results in a client's account balance, and format the result.
With entity beans in place for handling data access to most of our application, it makes sense to continue to leverage EJB for the business logic in our application. In this case, EJB session beans are a good fit. Session beans are complementary to entity beans and are designed specifically for handling business tasks. Additionally, they can be easily modularized, allowing mapping from a single business task to a session bean (as mentioned earlier, this is optimal). In this way, session beans can be "strung together" in logical ways, creating complete business processes. In this case, I am using the term business process to refer to a series of individual tasks. For example, obtaining a client's account balance or checking for availability of a new stock might be a business task; however, the complete business process of checking the balance, ensuring that enough is left to make a purchase, and then buying the stock comprises multiple individual tasks. Because each session bean can access the entity beans for the data it needs, one session bean may be used in multiple business processes without having to modify the single business task.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Presentation Layer
Last, but not least, is the presentation layer. As with the data layer, creating the presentation layer is another difficult task, as there are many decisions to be made. Additionally, this layer often has the most constraints upon it: clients have a variety of browsers and versions of browsers, as well as other Internet-capable devices; output may need to be in a specific format; speed of display may be a factor; and so on. In the Forethought application, the presentation layer must be able to serve multiple types of clients, and do it in a way that doesn't force a lot of duplication of content. JSP, XML, and XSL are all part of the solutions that will be examined for solving this problem.
As I'll be spending Volume II on the subject of presentation, I'll leave these details for a later discussion. However, this is not entirely for the sake of another book; it is also to show you that the details of the data and business layers are often completely isolated from the presentation layer. This means that two groups could design these at different times, or you could even develop a set of data stores and business rules without worrying about presentation until later (the approach taken by this book). This method forces you to uncouple these layers, which is critical to good application design. It also allows an easy conversion of an application to a set of web services; since your business layer is not specifically aimed at a web application, it is easy to expose beans and other business components as web services down the line. So I'll leave this area intentionally open for interpretation. Of course, this doesn't prevent a basic diagramming of how the presentation layer (be it servlets, web services, Java Swing, or anything else) interacts with the other layers in the application. Figure 2-3 shows this basic interaction.
Figure 2-3: The Forethought presentation layer
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Finalizing the Plans
By now it may seem that I have spent an eternity doing nothing but talking about the Forethought application. In reality, I have barely scratched the surface of a complete application design. Most companies require functional specifications, detailing what an application will do and the business needs it should serve. Often, technical design documents that specify the details in even more depth are required before a development team can begin work on a project. In some cases, an appropriate team might have to be assembled, which may involve contracting and consulting resources hired to supplement full-time employees. In other words, enjoy that I spent only a chapter on this subject, rather than a whole book! It's a luxury you would have only with a fictional company.
In any case, I have outlined the Forethought application well enough to give you an idea of the technologies and general techniques that will be used. Additionally, minimal architecture diagrams have been taking shape. With the data, business, and presentation layers all sketched out, the three separate layers can be combined into a single, overall application architecture. This complete picture is shown in Figure 2-4.
Figure 2-4: Completed Forethought application architecture
You can see that because of the separation between the layers, there is really no work to be done to "connect" these layers together. Java RMI and EJB services connect the business layer to the data layer, running through EJB and JNDI data access code. Connections between the presentation layer and the business layer can happen via RMI, normal Java network communication, or perhaps SOAP and similar protocols for web services interfaces. It's finally time, then, to close the book (proverbially of course!) on the application design for now, and move on to implementation.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
What's Next?
With the application designed and blueprints in place, you are now ready to begin filling in the details. The foundation is always the most critical portion of a house, as all other construction must be supported by it. In enterprise applications, particularly those on the Web, data itself is this fundamental layer. Data is the focus of the next chapter, and databases and directory servers are discussed as two options for storing this critical substance. Then, the data schema will be designed, the tables created, and preparations will be put in place for the rest of the application code.
Additionally, I will highlight how designing a data store is often almost completely unrelated to the specific application itself. By remaining general in the storage design and implementation, the foundation can be used and reused without having to be altered for different applications of the data, even for those applications you have yet to consider. This is key to the ever-changing landscape of web applications.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: Foundation
Enough talk—it's finally time to get on with some implementation. If you're much of a developer this is probably exciting news; all developers must take part in application design, and may even grow to enjoy it, but there's nothing like getting your hands dirty with some actual code. However, it isn't quite time to open your favorite IDE or editor and start punching out Java code. In fact, we'll get through this entire chapter without looking at a single line of Java. Instead, this chapter focuses on the data stores, creating the medium for holding the application's data. There's plenty of technical material, though, so don't get too worried just yet.
As mentioned in the first two chapters, the design of an application is its blueprint, and is crucial to its success. Now that you have this blueprint, you need to lay the foundation of the application with the data storage. Literally everything else in the application (as well as in other applications that may potentially use the Forethought data) depends on the decisions made here. I'll begin by discussing the overall design of the data. This involves defining the schema for the data without worrying about whether the data will be stored in a database, directory server, or any other specific technology.
Once you've determined how the information for the entire application will be laid out, you can begin to decide where specific data needs to be stored. In the case of the Forethought application, it has already been decided that data will be stored in one database (ignoring replication issues) and one directory server (ignoring failover instances). This simplifies the decision-making process quite a bit. The authentication data should be stored in the directory server, and the rest of the data housed within a database. All that is left, then, is designing the actual physical layout of the database and LDAP store, and implementing these designs. This will be detailed in the last part of the chapter.
The first step in the actual design of the data store is to identify each major section that we need to think about. Like the rest of the application design so far, good design is more about breaking up large pieces into small pieces than performing any mystical process. In the last chapter, the application was broken up into layers (data, business, and presentation); this chapter concentrates on the first of those, the data layer. That layer was broken up into the data itself, and data access; now the data can be broken up even
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Designing the Data Stores
The first step in the actual design of the data store is to identify each major section that we need to think about. Like the rest of the application design so far, good design is more about breaking up large pieces into small pieces than performing any mystical process. In the last chapter, the application was broken up into layers (data, business, and presentation); this chapter concentrates on the first of those, the data layer. That layer was broken up into the data itself, and data access; now the data can be broken up even further, into database tables and directory server objects. Through this process, a complex application becomes a series of small, manageable tasks that when put together make up a lot more than the sum of their parts.
So with that in mind, let's segregate the data. The first division is probably the easiest to handle: user data. Only basic information is required, so it's simple to determine that users should have their names and basic contact information stored in the database. In addition to user data, authentication data is a necessity. While authentication data will reside in a directory server, it still must contain a unique key that can be related back to the users in the database. This authentication data must also define permissions as well as simple username and password combinations.
Once this basic information about application users is in place, you can move on to the business details that Forethought is so concerned about. This is the account information that Forethought's clients are interested in, as well. There is a need to store accounts of the company's clients, transactions that involve those accounts, and investments the clients make. I'm distinguishing between transactions , where clients either deposit or withdraw funds, and investments , where clients invest money and yield either a profit or a loss. Then, like the authentication information, this information must have a tie to the user data store.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Databases
With the general data model done, we can now begin to cover the implementation details. In other words, we are finally through all the high-level talk and into the meat! In this section, you'll pick apart the data model and determine what portions belong in a database. You can then look at actually creating the tables, rows, columns, and keys that you'll need in the database to represent the data. Once you've accomplished that, we'll spend the next section looking at directory servers and performing the same task for the data that belongs in that physical medium.
Of course, the language of choice for databases is the Structured Query Language (SQL), and we'll use it to deal with databases here. Most databases now come with tools to make the creation of data structures simple; these are usually graphical and present a visual means of creating data structures. Additionally, a number of third- party tools are good for this sort of task (like SQL Navigator, already mentioned in Chapter 1). I'll focus on using pure SQL in this section, so the code will work on any database, on any platform, without you having to learn or buy a specific vendor's tool.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Directory Servers
Now that the database is ready to go, it's time to round out the data storage by working with a directory server, which at least in this case is much simpler than working with a database. Almost all directory servers come with several predefined data structures; in this example application, these structures are almost completely sufficient for our needs. In this section I'll discuss what information you'll need to store in the directory and how you can use pre-built and custom structures to handle these data needs.
Briefly, though, let me discuss directory servers at a high level. This is by no means a complete overview of directory servers or LDAP, but it should at least get you through this chapter. First, you should realize that a directory server is laid out hierarchically, instead of in the relational manner of a database. Here is where all of those tree structures you studied in college finally start to pay off. An instance of a directory server is identified uniquely by its organization. The organization in a directory server is analogous to a database schema in an RDBMS. So if you named your database schema "Forethought" (for you Oracle users, the SID might be "FTHT"), your directory server would have an organization of "Forethought" as well.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
What's Next?
You've made it through the creation of the data storage mediums, a major milestone in application design. As I have said several times, this portion of the framework will govern much of the rest of the application. Most notably, the data access layer is purely a reflection of the work already done here. We'll discuss this access in the next chapter, and work on allowing programmatic access to the data stores discussed here. This access will serve the rest of the application as well as components from other applications that may need data from the Forethought application.
Also in the next chapter, you'll get your first look at Enterprise JavaBeans, and in particular entity beans. We'll also examine the role of JNDI for allowing access to the directory server structures created in this chapter. In other words, we'll be running the gamut of Java approaches to accessing data in databases and directory servers. Once finished, you will have a functioning data layer for the application, with both a solid foundation and a set of sturdy beams, struts, and scaffolding upon which to build. Let's go onto this additional structure now (or at least after you've refilled your coffee and taken a deep breath).
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 4: Entity Basics
This chapter will look at entity beans as a means of accessing the Forethought application's data storage. I'll begin with simple entity beans to provide application entry points to the database, and address many questions common to entity bean development. Should you pass around the entity bean? Should you access the data exclusively through session beans, or directly through the entity beans? What are details objects, façade patterns, and good principles of entity bean design? All these questions will be answered, as I discuss not just writing EJB code, but writing effective EJB code.
At the end of this chapter, you will have the first entity bean created and deployed, ready for use. More importantly, you will have a good understanding of basic entity bean programming practices; you'll have looked at using container-managed persistence, package and class naming, handling method exposure through the remote interface, and more. In other words, you'll be ready for any basic entity bean problem that comes along, as well as for the advanced topics I'll address in Chapter 5.
To access the data that will be stored in the database, you can use EJB's entity bean functionality. Keep in mind, however, that this is not by any means a book on how to write Enterprise JavaBeans; for that I recommend Richard Monson-Haefel's excellent book, Enterprise JavaBeans (O'Reilly). Here, I'll simply focus on using EJBs correctly, and detail some useful design patterns.
In addition to looking at some design patterns and actual code, you must be familiar with two technologies that are intrinsic to EJBs: RMI and JNDI. Remote Method Invocation, or RMI, is the basis of all Enterprise JavaBeans calls. In a nutshell, RMI causes a remote call to a Java object over the network to behave exactly like a local call. The Java Naming and Directory Interface, or JNDI, allows objects to be bound into a namespace and then referenced by other objects. The namespace in this case is purely an abstract concept, but organization of Java objects and information in this manner does work well; all components of an application can use this single means of storage. Of course, like any other technology, RMI and JNDI require resources. JNDI requires memory in which to store the objects bound into its contexts, and both require runtime resources to operate. For example, looking up an object in the JNDI registry is more time-consuming than referencing a local object, and executing an RMI call is more expensive in terms of resources than executing a local method invocation. As always, you must focus on logical tradeoffs, and use both technologies only when needed. As usual, you should have a good reason for everything. And now, assuming that you are comfortable with these technologies, let's look at entity beans in detail.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Basic Design Patterns
To access the data that will be stored in the database, you can use EJB's entity bean functionality. Keep in mind, however, that this is not by any means a book on how to write Enterprise JavaBeans; for that I recommend Richard Monson-Haefel's excellent book, Enterprise JavaBeans (O'Reilly). Here, I'll simply focus on using EJBs correctly, and detail some useful design patterns.
In addition to looking at some design patterns and actual code, you must be familiar with two technologies that are intrinsic to EJBs: RMI and JNDI. Remote Method Invocation, or RMI, is the basis of all Enterprise JavaBeans calls. In a nutshell, RMI causes a remote call to a Java object over the network to behave exactly like a local call. The Java Naming and Directory Interface, or JNDI, allows objects to be bound into a namespace and then referenced by other objects. The namespace in this case is purely an abstract concept, but organization of Java objects and information in this manner does work well; all components of an application can use this single means of storage. Of course, like any other technology, RMI and JNDI require resources. JNDI requires memory in which to store the objects bound into its contexts, and both require runtime resources to operate. For example, looking up an object in the JNDI registry is more time-consuming than referencing a local object, and executing an RMI call is more expensive in terms of resources than executing a local method invocation. As always, you must focus on logical tradeoffs, and use both technologies only when needed. As usual, you should have a good reason for everything. And now, assuming that you are comfortable with these technologies, let's look at entity beans in detail.
First, you need to address access to entity beans (yes, I'm getting to the code; just be patient!). This might seem like a simple topic, but debates have been raging for years on various email lists concerning the means of accessing entity beans. The arguments center over whether entity beans should be accessed directly by an application (be it a servlet, Java application, or some other code fragment), or whether these calls should pass through a session bean, which then " proxies" the call to the entity bean. In the latter case, more RMI communication is involved, more JNDI lookups occur, and serialization may be necessary in passing returned values. However, accessing entity beans through some sort of proxy is still the preferred means of access.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Coding the Bean
It's finally time to write some code. If you are new to EJB, you should pick up the aforementioned Enterprise JavaBeans and skim through Chapter 4 before continuing on. That should give you enough of a basic foundation to understand this chapter, as I'm going to move through the basic entity bean code pretty quickly.
I'll start the entity bean work with the office data structure. Remember the OFFICES table from last chapter? The table structure is shown again in Figure 4-1 for reference.
Figure 4-1: The office data structure
I'll use this structure for the first entity bean, as it has a very simple structure. It also does not depend on any other objects (i.e., it has no foreign keys), a subject I will address in the next chapter. Dependent objects introduce some additional considerations, but I will look at those when we start to code beans for tables with foreign keys, like the USERS table. For the time being, it's enough to know that this office structure is as simple as it gets. You need to store the ID (an int), the city (a String), and the state (another String).
As this bean is simple in nature, it is a perfect candidate for container-managed persistence (CMP). There are no special JDBC calls that need to be made, no multiple-table queries, and no explicit data caching that needs to be performed. In the absence of these special cases, CMP is almost always a better choice than bean-managed persistence (BMP). While CMP beans are not truly portable yet, as each container generates specific implementation classes for that product, the basic classes I'll look at in a CMP bean are portable. In other words, you won't be able to take a complete JAR file (with implementation classes) from BEA Weblogic and deploy it on Lutris Enhydra, but you will be able to take the user-coded classes from this chapter and use them to generate classes for both BEA Weblogic and Lutris Enhydra. The resultant JARs can then be deployed on the respective application servers. This adds a bit of work, but is as close to complete portability as is possible in today's EJB containers. It does allow us to write vendor-neutral code and not have to focus on a specific application server in this chapter.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Deploying the Bean
At this point, you've completed the code for your entity bean, and now you need to deploy the bean. This involves creating a deployment descriptor for the bean and then wrapping the entire bean into a deployable unit. I'll cover each of these steps in the following sections.
To wrap all these classes into a coherent unit, you must create an XML deployment descriptor. These descriptors replace the horrible serialized deployment descriptors from EJB 1.0. XML deployment descriptors eliminate one vendor-dependent detail: the descriptor is standardized across all application servers. Notice that the document type definition (DTD) referred to in the DOCTYPE declaration refers to a Sun file, ensuring that no vendors add their own tags or extensions to the descriptor. If your server requires you to use a different DTD, you may have a serious problem on your hands; you may want to consider switching to a standards-based application server immediately. And if DTDs, elements, tags, and these other XML terms are Greek to you, pick up Java and XML(O'Reilly), by yours truly, to get answers to your XML-related questions.
Example 4-7, the deployment descriptor for the office entity bean, contains entries only for that bean, detailing its home, remote, implementation, and primary key classes. These are all required elements for an entity bean, as is specifying that the bean is not reentrant and specifying the persistence type, which in our case is container-managed. Later on, we'll add entries for numerous other entity beans that we will code and add to the application. Because we are deploying a CMP bean, the fields that must be handled by the container are listed; in this case, these are all the fields in the OfficeBean class. We also give the bean a name to be used, OfficeBean.
If you are familiar with EJB deployment descriptors, you might notice that I have left out the assembly-descriptor element and related subelements that allow permission specification for beans and their methods. That's so you can focus on the bean right now, and deal with security later. Don't worry, though; I'll get to all of this before we're done with our application. Leaving it out for now will allow the container to generate default permissions.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
What's Next?
You should now have a good idea of common architectural problems related to basic entity beans. Primary keys, package naming, deployment descriptors, and more should all be at your fingertips. Once you've mastered these concepts, you're ready to look at some more interesting subjects. In the next chapter, I'll cover handling primary key values, detail objects, and more. So make sure that you understand the basics in this chapter, and keep reading.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 5: Advanced Entities
In this chapter, we'll dig into some more interesting entity bean topics. I'll start by looking at how entity beans can and should abstract database IDs and sequences from business-oriented clients. You'll see how session beans can be used for these sorts of tasks, learn about database access through JDBC in beans, and put all these pieces into a coherent whole. From there I'll move on to discussing entity bean value objects, serialization of these objects, and decreasing RMI traffic.
I'll also discuss when to use container-managed persistence (CMP) and when to use bean-managed persistence (BMP). This leads you from accessing the database to accessing the directory server set up for usernames and authentication data. I'll also cover the variety of ways you can access a directory server. At this point, the Java Naming and Directory Interface (JNDI) will enter the picture, too. By the end of this chapter, you'll have several new entity beans, a session bean, a more advanced Office bean, and a thorough understanding of entity bean architecture.
The most common problem in working with entity beans is dealing with primary keys. The underlying principle is that EJB components should represent business objects and business entities. In other words, if something isn't used in the business of an application, it shouldn't be visible to the bean developer. What that means in terms of the entity beans so far is that you need to hide the details of offices' ID fields: they have no business meaning, and are useful only at the database level. Therefore, you don't want a user to pass in a value when creating a new office. Instead, the bean implementation (hidden to the bean client) should assign a viable ID at office creation. Straying from this principle will result in session beans and servlets having to deal with IDs that have no meaning outside of the database layer. The only use for an office's ID is in locating the office or in tying in the office to a related structure, like a user. For this reason, it is OK to allow a bean client to find out an office's ID, but it's not OK for that client to create the office by specifying an ID. This is in contrast to the current
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
IDs, Sequences, and CMP
The most common problem in working with entity beans is dealing with primary keys. The underlying principle is that EJB components should represent business objects and business entities. In other words, if something isn't used in the business of an application, it shouldn't be visible to the bean developer. What that means in terms of the entity beans so far is that you need to hide the details of offices' ID fields: they have no business meaning, and are useful only at the database level. Therefore, you don't want a user to pass in a value when creating a new office. Instead, the bean implementation (hidden to the bean client) should assign a viable ID at office creation. Straying from this principle will result in session beans and servlets having to deal with IDs that have no meaning outside of the database layer. The only use for an office's ID is in locating the office or in tying in the office to a related structure, like a user. For this reason, it is OK to allow a bean client to find out an office's ID, but it's not OK for that client to create the office by specifying an ID. This is in contrast to the current OfficeHome interface, which has a create( ) method that looks like this:
public Office create(Integer id, String city, String state)
    throws CreateException, RemoteException;
The most common (and unfortunately, the worst) way to create an ID has been for developers to code logic into their entity bean's ejbCreate( ) method that directly interfaces with the database. This logic varies from selecting a random number to obtaining the next number from a database sequence (particularly common in Oracle databases) or retrieving the highest value in use and adding 1. There are so many different problems with this approach, though, that it should immediately be thrown out as an option in your bean programming. The first and most important problem is that this method is not vendor-neutral or database-neutral, and leaves your code working only on the specific setup you are using. Additionally, going to the database for a sequence value or the highest existing value results in additional JDBC calls, slowing the entire application. And the logic of picking a random or semi-random number is unreliable, at best.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Details, Details, Details
Continuing on with a look at common problems in EJB, it's time to move to one area that is fairly well understood: the overhead of RMI traffic. More often than not, more time is spent waiting for networks to respond than on actual processing when dealing with EJB. So far, I have spent a lot of time talking about creating a new entity, such as the Forethought office. In that case, very little "back-and-forth" traffic occurs:
Object ref = context.lookup("java:comp/env/ejb/OfficeHome");
OfficeHome home = (OfficeHome)
    PortableRemoteObject.narrow(ref, OfficeHome.class);
Office office = home.create("Dallas", "TX");
In this case, once the home interface of the bean is located, a single call creates the new office. However, when obtaining information about an office, more calls are needed:
String city = office.getCity(  );
String state = office.getState(  );    
While these two calls look pretty harmless, each requires a round-trip RMI call. The remote stub has its method invoked, initiates a remote method invocation, waits for a response, and returns that response. All this depends on network latency and all the other costly issues that surround any network transmission. While even this doesn't seem too bad, take a look at a slightly more complex object:
String sku = product.getSKU(  );
String name = product.getName(  );
String description = product.getDescription(  );
float price = product.getPrice(  );
// etc...
Here, multiple trips over the network are required for these simple method calls, and the application quickly becomes bogged down waiting on even the fastest networks. This is a common peril in using EJB. Happily, though, it can easily be remedied.
Instead of returning field-level values through these calls, you can set your beans up to return object maps . In this case, an object map is a normal Java object that corresponds to the entity returning it. This object is then used to find out information about the entity. In this way, a single remote call occurs, and a local object map is returned. This map has all the information a client might need to query about the entity, and therefore this information can be obtained through local calls, instead of expensive remote calls. Let's look at doing this with the Office bean and see exactly how this problem can be handled.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Data Modeling
A final couple of words on entity beans are merited before moving on. The Office bean has remained very simple so far, allowing you to overlook a few problems related to dealing with entity beans in a large application. This simplicity exists for two reasons: first, the bean stands on its own, and second, it is a frequently changed object. These two facts are discussed in the following sections.
The fact that an office is a complete entity means that it is an independent data object. In other words, a Forethought office does not depend on any other data to be complete. Additionally, an office has meaning on its own. A states table, for example, might not have this quality; for our purposes, a state's name and abbreviation are not really useful on their own, and the state has purpose only within the context of another entity that references the states table. In this case, you would want the client to deal with the overall office entity, perhaps setting its name, and the bean would then use the states bean to work with that entity. In that way, the states entity becomes a dependent object. On the other hand, the office entity is an independent object.
It is also important to understand that just because an entity is used by another entity, it is not necessarily dependent. The office entity is again a perfect example: it is referenced by the users entity, specifying the office the user works in. But the office entity is not dependent, because it has business meaning on its own. There are many cases where the office may need to be used alone, such as locating the nearest Forethought office. Because of these uses, you don't want to prevent access to the office entity; however, you would prevent similar access for states.
EJB 2.0 provides for relationships between beans, and it is here that dependent objects begin to play an important role in the application. The new CMP 2.0 in the EJB specification allows for much easier handling of this information, as you'll see in examples in the appendixes and throughout the rest of the book. Because that's a fairly routine EJB practice, though, I'll leave further details about bean relationships to basic EJB books, and not address it here. Other than a few additional abstract methods and a few entries in a deployment descriptor, the container takes care of all the relationship work, so there's no special work required on your part.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Filling in the Blanks
Content preview·Buy PDF of this chapter|