BUY THIS BOOK
Add to Cart

Print Book $49.99


Add to Cart

Print+PDF $64.99

Add to Cart

PDF $39.99

Safari Books Online

What is this?

Add to UK Cart

Print Book £35.50

What is this?

Looking to Reprint or License this content?


Enterprise JavaBeans 3.0
Enterprise JavaBeans 3.0, Fifth Edition By Richard Monson-Haefel, Bill Burke
May 2006
Pages: 760

Cover | Table of Contents


Table of Contents

Chapter 1: Introduction
This book is about Enterprise JavaBeans 3.0, the latest version of the Enterprise JavaBeans specification, and its counterpart, the new Java Persistence specification. Just as the Java platform has revolutionized the way we think about software development, the Enterprise JavaBeans (EJB) and Java Persistence specifications have revolutionized the way we think about developing mission-critical enterprise software. They combine server-side components with distributed object technologies, asynchronous messaging, web services, and persistence to greatly simplify the task of application development. It automatically takes into account many of the requirements of business systems, including security, resource pooling, concurrency, and transactional integrity.
This book shows you how to use Enterprise JavaBeans and Java Persistence to develop scalable, portable business systems. But before we can start talking about EJB itself, we'll need a brief introduction to the technologies addressed by EJB and Java Persistence, such as component models, distributed objects, asynchronous messaging, and web services. In Chapter 2, we'll learn about the overall architecture that EJB and Persistence provide. In Chapters 3 and 4, we'll look at how these APIs are integrated together in a Java enterprise environment. The rest of the book is devoted to developing enterprise and entity beans for an imaginary business, and discussing advanced issues.
It is assumed that you're already familiar with Java; if you're not, Learning Java (O'Reilly) is an excellent introduction, as is Head First Java (O'Reilly). This book also assumes that you're conversant in the JDBC API, or at least in SQL. If you're not familiar with JDBC, see Database Programming with JDBC and Java (O'Reilly).
One of Java's most important features is platform independence. Since it was first released, Java has been marketed as "write once, run anywhere." While the hype has gotten a little heavy-handed at times, code written with Sun's Java programming language is remarkably platform-independent. EJB and Java Persistence aren't just platform-independent; they are also implementation-independent. If you've worked with JDBC, you know a little about what this means. Not only can the JDBC API run on a Windows machine or on a Unix machine, it can also access relational databases of many different vendors (DB2, Oracle, MySQL, MS SQL Server, etc.) by using different JDBC drivers. You don't have to code to a particular database implementation; just change JDBC drivers, and you change databases. It's the same with EJB and Java Persistence. Ideally, an EJB component (an enterprise bean) or a Java Persistence object (an entity bean) can run in any application server that implements these specifications. This means that you can develop and deploy your EJB business system in one server, such as BEA's WebLogic, and later move it to a different EJB server, such as Pramati, Sybase's EAServer, or IBM's WebSphere, or to an open source project such as JBoss, Apache Geronimo, or JOnAS. Implementation independence means that your business components do not depend on the brand of server, which gives you many more options before, during, and after development and deployment.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Server-Side Components
Object-oriented languages such as Java, C++, C#, Python, and Ruby are used to write software that is flexible, extensible, and reusable—the three axioms of object-oriented development. In business systems, object-oriented languages are used to improve development of GUIs, to simplify access to data, and to encapsulate the business logic. The encapsulation of business logic into business objects is a fairly recent focus in the information-technology industry. Business is fluid, which means that a business's products, processes, and objectives evolve over time. If the software that models the business can be encapsulated into business objects, it becomes flexible, extensible, and reusable, and therefore evolves as the business evolves.
A server-side component model may define an architecture for developing distributed business objects that combines the accessibility of distributed object systems with the fluidity of objectified business logic. Server-side component models are used on middle-tier application servers, which manage the components at runtime and make them available to remote clients. They provide a baseline of functionality that makes it easy to develop distributed business objects and assemble them into business solutions.
Server-side components can also be used to model other aspects of a business system, such as presentation and routing. A Java servlet, for example, is a server-side component that generates HTML and XML data for the presentation layer of a web application (Struts and JSF components are also examples of this type of server-side component). EJB message-driven beans, discussed later in this book, are server-side components that can be used to consume and process asynchronous messages.
Server-side components, like other components, can be bought and sold as independent pieces of executable software. They conform to a standard component model and can be executed without direct modification in a server that supports that component model. Server-side component models often support attribute-based programming, which allows the runtime behavior of the component to be modified when it is deployed, without having to change the programming code in the component. Depending on the component model, the server administrator can declare a server-side component's transactional, security, and even persistence behavior by setting these attributes to specific values.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Persistence and Entity Beans
Persistence is a higher-level abstraction above JDBC. The persistence layer maps objects to database storage so that they can be queried, loaded, updated, or removed without having to go through a verbose API such as JDBC. In older versions of EJB, persistence was part of the EJB platform. Starting with EJB 3.0, persistence has been spun off to its own specification, called the Java Persistence API.
The Java Persistence API defines a way to map regular, plain old Java objects (sometimes referred to as POJOs) to a database. These plain Java objects are called entity beans. Entity beans are like any other Java class, except that they have been mapped, using Java Persistence metadata, to a database. Therefore, they may be inserted and loaded from a database without the developer writing any JDBC connection code or reading from result sets. The Java Persistence API also defines a query language that has features that parallel those in SQL, but is tailored to work with Java objects rather than a raw relational schema.
In the EJB 2.1 specification, entity beans were very "heavyweight" and dependent on the application server and the entire Java EE runtime environment. In Java Persistence, entity beans are regular Java objects that are managed by a persistence service. Unlike their EJB 2.1 counterparts, entities in Java Persistence are not required to implement any special spec-defined interfaces or classes. Another weakness of the older specification was that it left individual vendors to decide how an object should be mapped to a particular database representation. This made EJB 2.1 entity beans mostly nonportable between vendors. The new Java Persistence specification defines a complete object to relational mapping (ORM) so that entity beans can be ported easily from vendor to vendor. Furthermore, because entity beans are now plain Java objects, they are not just portable between application servers; they can be used in regular Java applications outside of an application server and can even be used to transfer data between a client and a server. This makes designs simpler and more compact.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Asynchronous Messaging
In addition to supporting RMI-based distributed business objects, Enterprise JavaBeans supports asynchronous messaging. An asynchronous messaging system allows two or more applications to exchange information in the form of messages. A message, in this case, is a self-contained package of business data and network routing headers. The business data contained in a message can be anything—depending on the business scenario—and usually contains information about some business transaction. In enterprise systems, messages inform an application of some event or occurrence in another system.
Asynchronous messages may be transmitted from one application to another on a network using message-oriented middleware (MOM). MOM products ensure that messages are properly distributed among applications. In addition, MOM usually provides fault-tolerance, load-balancing, scalability, and transactional support for enterprises that need to reliably exchange large quantities of messages. MOM vendors use different message formats and network protocols for exchanging messages, but the basic semantics are the same. An API is used to create a message, give it a payload (application data), assign it routing information, and then send the message. The same API is used to receive messages produced by other applications.
In modern enterprise-messaging systems, applications exchange messages through virtual channels called destinations . When you send a message, it's addressed to a destination, not to a specific application. Any application that subscribes to or registers an interest in that destination may receive that message. In this way, the applications that receive messages and those that send messages are decoupled. Senders and receivers are not bound to each other in any way and may send and receive messages as they see fit.
Enterprise JavaBeans integrates the functionality of MOM into its component model. This integration extends the EJB platform so that it supports both RMI and asynchronous messaging. EJB 3.0 supports asynchronous messaging through the Java Message Service (JMS) and a new component called the message-driven bean. In addition to JMS, message-driven beans can support other synchronous and asynchronous messaging systems.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Web Services
Web services represent the latest wave in distributed computing. Although the term web services is bandied about quite a bit, arriving at a concrete definition is difficult because web services is, at the highest level, not specific to any particular technology or platform. It's often defined in fairly abstract terms, like "a substrate for building distributed applications using software running on different operating systems and devices" or "self-contained, self-describing, modular applications that can be published, located, and invoked across the Web." Of course, these quotes are taken out of context, but that's the essential point: you need some kind of context to define web services. Here's my definition of web services that has meaning in the context of Java EE, EJB, .NET, and most other web services platforms:
Web services are network applications that use SOAP and WSDL to exchange information in the form of XML documents.
To understand this definition, you need to understand SOAP and WSDL. Here are brief definitions of these terms:
SOAP 1.1
Simple Object Access Protocol (SOAP) is an XML grammar, developed by Microsoft, IBM, and others, that is currently under the auspices of the W3C. It's an application protocol used in both RPC and asynchronous messaging. SOAP is very flexible and extensible and, unlike its predecessors (DCE RPC, CORBA IIOP, Java RMI-JRMP, and DCOM), it's been endorsed and adopted by just about every major vendor. (If you're not familiar with XML, see Java and XML or XML in a Nutshell, both from O'Reilly.)
WSDL 1.1
The Web Service Description Language (WSDL) is another XML grammar, developed by Microsoft and IBM under the auspices of the W3C. It is an XML-based Interface Definition Language (IDL) that can be used to describe web services, including the kind of message format expected, the Internet protocol used, and the Internet address of the web service.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Titan Cruises: An Imaginary Business
To make things easier and more fun, we discuss all the concepts in this book in the context of an imaginary business, a cruise line called Titan Cruises. A cruise line makes a particularly interesting example because it incorporates several different businesses: it has ship cabins that are similar to hotel rooms; it serves meals like a restaurant does; it offers various recreational opportunities; and it needs to interact with other travel businesses.
This type of business is a good candidate for a distributed object system because many of the system's users are geographically dispersed. Commercial travel agents, for example, who need to book passage on Titan ships need to access the reservation system. Supporting many—possibly hundreds—of travel agents requires a robust transactional system to ensure agents have access and reservations are completed properly.
Throughout this book, we will build a fairly simple slice of Titan's EJB system that focuses on the process of making a reservation for a cruise. This exercise will give us an opportunity to develop Ship, Cabin, TravelAgent, ProcessPayment, and other enterprise and entity beans. In the process, you will need to create relational database tables for persisting data used in the example. It is assumed that you are familiar with relational database management systems and that you can create tables according to the SQL statements provided.
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?
To develop business objects using EJB and Java Persistence, you have to understand the life cycles and architectures of EJB components and entity bean objects. This means understanding the concepts of how EJB components are managed and made available as distributed objects. Developing an understanding of the EJB and Java Persistence architectures, and how they fit into the larger Java EE environment, is the focus of the next two chapters.
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: Architectural Overview
To use Enterprise JavaBeans and Java Persistence effectively, you need to understand their architectures. This chapter explores the core of the EJB and Java Persistence architectures: how enterprise beans are distributed as business objects and how they interact with Java Persistence. Chapter 3 explores the services and resource-management techniques supported by EJB.
In order to be truly versatile, the EJB component design had to be smart. For application developers, assembling enterprise beans requires little or no expertise in the complex system-level issues that often plague three-tier development efforts. While EJB makes the process easier for application developers, it also provides EJB server developers with a great deal of flexibility in how they support the EJB specification.
Java Persistence also makes it fairly easy for developers to write objects that can be persisted to a relational database. Writing a persistent entity bean can be as easy as using a few strategically placed annotations with little to no information about the database. Although it is easy to prototype entity beans, the specification is rich enough to provide facilities for more complex database mappings.
Entity beans in the Java Persistence 1.0 specification are available only as plain old Java objects (POJOs), and are mapped to tables in a relational database. Unlike other EJB types, entities can be allocated, serialized, and sent across the network like any other POJO.
A good rule of thumb is that entity beans model business concepts that can be expressed as nouns. For example, an entity bean might represent a customer, a piece of equipment, an item in inventory, or even a place. In other words, entity beans model real-world objects; these objects are usually persistent records in some kind of database. Our hypothetical cruise line will need entity beans that represent cabins, customers, ships, etc.
A good way to understand the design of entity beans is to look at how you'd go about implementing one. To implement an entity bean, you need to define a bean class and decide what field you will use as the identifier (primary key) of that bean class:
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 Entity Bean
Entity beans in the Java Persistence 1.0 specification are available only as plain old Java objects (POJOs), and are mapped to tables in a relational database. Unlike other EJB types, entities can be allocated, serialized, and sent across the network like any other POJO.
A good rule of thumb is that entity beans model business concepts that can be expressed as nouns. For example, an entity bean might represent a customer, a piece of equipment, an item in inventory, or even a place. In other words, entity beans model real-world objects; these objects are usually persistent records in some kind of database. Our hypothetical cruise line will need entity beans that represent cabins, customers, ships, etc.
A good way to understand the design of entity beans is to look at how you'd go about implementing one. To implement an entity bean, you need to define a bean class and decide what field you will use as the identifier (primary key) of that bean class:
Primary key
The primary key is something that provides a pointer into the database. It gives the entity bean class's identity both in memory as an object and in the database as a row in a table. The primary key can be a class or a primitive type.
Bean class
The entity bean class may contain business logic but is usually just the object representation of persistence storage. In general, only business logic like validation should be placed in the entity bean class. The bean class is a POJO that does not have to implement any interface or even be serializable. It must be tagged with the @javax.persistence.Entity annotation and have at least one field or getter method that is designated as the primary key of the entity bean class in the database. This is usually done with the @javax.persistence.Id annotation. Entities have other annotations available to define a full object-relational database mapping 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!
The Enterprise Bean Component
Enterprise JavaBeans server-side components come in two fundamentally different types: session beans and message-driven beans . Session beans are server-side components that can be accessed using a variety of distributed object protocols. Message-driven beans process messages asynchronously from systems like the JMS, legacy systems, and web services. All EJB servers must at least support a JMS-based message-driven bean, but they may also support other types of message-driven beans.
Session beans are extensions of the client application that manage processes or tasks. A Ship entity bean provides methods for doing things directly to a ship, but it doesn't say anything about the context under which those actions are taken. Booking passengers on the ship requires that we use a Ship entity, but it also requires a lot of things that have nothing to do with the ship itself: we'll need to know about passengers, ticket rates, schedules, and so on. A session bean is responsible for this kind of coordination. Session beans tend to manage particular kinds of activities, such as the act of making a reservation. They have a lot to do with the relationships between different entity beans. A TravelAgent session bean, for example, might use a Cruise, a Cabin, and a Customer—all entity beans—to make a reservation.
Similarly, message-driven beans coordinate tasks involving other session and entity beans. Message-driven beans and session beans differ primarily in how they are accessed. While a session bean provides a remote interface that defines which methods can be invoked, a message-driven bean subscribes to or listens for messages. It responds by processing the message and managing the actions that other beans take. For example, a ReservationProcessor message-driven bean would receive asynchronous messages—perhaps from a legacy reservation system—from which it would coordinate the interactions of the Cruise, Cabin, and Customer beans to make a reservation.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Using Enterprise and Entity Beans
Let's look at how a client would use an enterprise bean to do something useful. In this example, we'll create a TravelAgent session bean that creates a reservation for a remote client. This TravelAgent EJB will interact with various entity and other session bean types.
Entity beans are useful for representing data and describing business concepts that can be expressed as nouns, but they're not very good at representing a process or a task. A Ship bean provides methods and behavior for doing things directly to a ship, but it does not define the context under which these actions are taken. We don't want business logic in the client application—that's why we went to a multitier architecture in the first place. Similarly, we don't want this kind of logic in our entity beans that represent ships and cabins. Booking passengers on a ship or scheduling a ship for a cruise is a type of activity or function of the business, not of the Ship or Cabin bean, and is therefore expressed in terms of a process or task.
Session beans act as agents that manage business processes or tasks for the client; they're the appropriate place for business logic. A session bean is not persistent; nothing in a session bean maps directly into a database or is stored between sessions. Session beans work with entity beans, data, and other resources to control taskflow . Taskflow is the essence of any business system, because it expresses how entities interact to model the actual business. Session beans control tasks and resources but do not themselves represent data.
The term taskflow was coined specifically for this book. It's derived from the term workflow, which is frequently used to describe the management of business processes that may span several days with lots of human intervention. In contrast to workflow, taskflow is used in this book to describe the interactions of beans within a single transaction that takes only a few seconds to execute.
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 Bean-Container Contract
The environment that surrounds the beans on the EJB server is often called the container. The container is more a concept than a physical construct. It acts as an intermediary between the bean and the EJB server. It manages the EJB objects and helps these constructs manage bean resources and provide services such as transactions, security, concurrency, and naming at runtime. The distinction between the container and the server is not clearly defined, but the EJB specification defines the component model in terms of the container's responsibilities, so we will follow that convention here.
Enterprise bean components interact with the EJB container through a well-defined component model. All EJB types register for various life cycle events that the EJB container emits. They register for these events by annotating a method within their bean class that is interested in the specific event. At runtime, the container invokes these annotated methods on the bean instance when relevant events occur. For example, after the container allocates and injects referenced services into an EJB instance, it will call a method annotated with @javax.annotation.PostConstruct on the EJB's bean class if one is provided. This call gives the bean instance an opportunity to do any additional initialization before the EJB services any request. Other callback methods can be used by the bean class in a similar fashion. EJB defines when these various callback methods are invoked and what can be done within their contexts.
In EJB 3.0, your code does not have to implement empty callback methods like it does in older versions of the EJB specification. You write code only for those events that you are interested in. Beans that implement callback methods usually access resources that aren't managed by the EJB system. Enterprise beans that wrap legacy systems often fall into this category.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Summary
This chapter covered a lot of ground in describing the basic architecture of an EJB and Java Persistence system. At this point, you should understand that beans are business object components. Session beans have remote and local interfaces that define the public business methods of the bean. Message-driven and entity beans do not have component interfaces. Entity beans are plain Java objects. The bean class is where the state and behavior of the bean are implemented.
There are three basic kinds of beans: entity, session, and message-driven. Entity beans are persistent and represent a person, place, or thing. Session beans are extensions of the client and embody a process or a taskflow that defines how other beans interact. Session beans are not persistent: they receive their state from the client and live only as long as the client needs them. Message-driven beans are integration points that allow other applications to interact with EJB applications using JMS or some other JCA 1.5-compliant resource. Message-driven beans, like stateless session beans, are not persistent and do not maintain conversational state.
The EJB proxy stub is a conceptual construct that delegates method invocations to session beans from the client and helps the container manage the enterprise bean at runtime. The clients of session beans do not interact with the instances of the session bean class directly. Instead, the client software interacts with the proxy stub. The proxy stub implements the remote and/or local interface and expands the bean class's functionality. Entity beans are created in the same way as any other Java object and are managed by the EntityManager service.
Beans interact with their containers through the well-defined bean-container contract. This contract provides callback methods, the EJBContext , and the JNDI environment-naming context. The callback methods notify the bean class that it is involved in a life cycle event. The
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: Resource Management and Primary Services
Chapter 2 discussed the basic architecture of Enterprise JavaBeans and Java Persistence, including the relationship between the bean class, the EJB container, and the EntityManager service. These artifacts define a common model for distributed server-side components as well as a persistence model that can be used on the server or in standalone applications. But this model isn't enough to make EJB interesting or even particularly useful. EJB servers also manage the resources used by beans, and can manage thousands or even millions of distributed objects simultaneously. They must manage how distributed objects use memory, threads, database connections, processing power, and more. Furthermore, the EJB specification defines interfaces that help developers take advantage of these common practices.
EJB servers support six primary services: concurrency, transaction management, persistence, object distribution, naming, and security. These services provide the kind of infrastructure that is necessary for a successful three-tier system. EJB also supports two additional services: asynchronous messaging and a timer service.
This chapter discusses the resource-management facilities and the primary services that are available to Enterprise JavaBeans.
A large business system with many users can easily have thousands or even millions of objects in use simultaneously. As the number of interactions among these objects increases, concurrency and transactional concerns can degrade the system's response time and frustrate users. EJB servers increase performance by synchronizing object interactions and sharing resources.
There is a relationship between the number of clients and the number of distributed objects that are required to service them. Not surprisingly, the larger the client population, the more distributed objects are needed. At some point, the increase in clients affects performance and diminishes throughput. EJB explicitly supports two mechanisms that make it easier to manage large numbers of beans at runtime: instance pooling and activation. In addition, EJB supports the use of the Java EE Connector Architecture (Java EE Connectors) for managing resource connections. As the number of distributed objects and clients increases, the number of resource connections also increases. Java EE Connectors work with the EJB container to manage connections to databases, enterprise messaging, ERP, legacy systems, and other types of resources.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Resource Management
A large business system with many users can easily have thousands or even millions of objects in use simultaneously. As the number of interactions among these objects increases, concurrency and transactional concerns can degrade the system's response time and frustrate users. EJB servers increase performance by synchronizing object interactions and sharing resources.
There is a relationship between the number of clients and the number of distributed objects that are required to service them. Not surprisingly, the larger the client population, the more distributed objects are needed. At some point, the increase in clients affects performance and diminishes throughput. EJB explicitly supports two mechanisms that make it easier to manage large numbers of beans at runtime: instance pooling and activation. In addition, EJB supports the use of the Java EE Connector Architecture (Java EE Connectors) for managing resource connections. As the number of distributed objects and clients increases, the number of resource connections also increases. Java EE Connectors work with the EJB container to manage connections to databases, enterprise messaging, ERP, legacy systems, and other types of resources.
The concept of pooling resources is not new. It's common to pool database connections so that the business objects in the system can share database access. This trick reduces the number of database connections needed, which reduces resource consumption and increases throughput. The Java EE Connector Architecture (JCA) is frequently the mechanism employed by EJB containers when pooling connections to databases and other resources, and is covered a little later. Most EJB containers also apply resource pooling to server-side components; this technique is called instance pooling. Instance pooling reduces the number of component instances—and therefore resources—needed to service client requests.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Primary Services
Many value-added services are available for distributed applications. This book looks at eight value-added services that are called the primary services because they are required to complete the Enterprise JavaBeans platform. The primary services include concurrency, transactions, persistence, distributed objects, asynchronous messaging, a timer service, naming, and security. EJB servers automatically manage all of the primary services. This capability relieves application developers from the task of mastering these complicated services. Instead, developers can focus on defining the business logic that describes the system and can leave the system-level concerns to the EJB server. The following sections describe each primary service and explain how they are supported by EJB.
Concurrency is important to all the bean types, but it has different meanings for each type.

Section 3.2.1.1: Concurrency with session and entity beans

Session beans do not support concurrent access. This limitation makes sense if you consider the nature of stateful and stateless session beans. A stateful bean is an extension of one client and serves only that client. It doesn't make sense to make stateful beans concurrent if they are used only by the clients that created them. Stateless session beans don't need to be concurrent because they don't maintain state that needs to be shared. The scope of the operations performed by a stateless bean is limited to the scope of each method invocation. Because neither stateful nor stateless session beans represent shared data, there is no need for concurrency.
Because EJB servers handle concurrency, a bean's methods do not have to be made thread-safe. In fact, the EJB specification prohibits the use of the synchronized keyword. Prohibiting the use of the thread synchronization primitives prevents developers from thinking that they control synchronization and enhances the performance of bean instances at runtime. In addition, the EJB specification explicitly prohibits beans from creating their own threads. In other words, as a bean developer, you cannot create a thread within a bean. The EJB container has to maintain complete control over the bean in order to properly manage concurrency, transactions, and persistence. Allowing the bean developer to create arbitrary threads would compromise the container's ability to track what the bean is doing and would make it impossible for the container to manage the primary services.
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?
The first three chapters of this book gave you a foundation on which to develop Enterprise JavaBeans components and applications. While we haven't gone into detail, we've shown you most of the topics that you'll be dealing with. Beginning with Chapter 4, you will develop your own beans and learn how to apply them in EJB 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 4: Developing Your First Beans
The primary goal of the EJB 3.0 and Java Persistence specifications was to make it as easy as possible to write and deploy an EJB-based application. Creating an application is as easy as compiling your code, jarring up your classes, and running your application server. This chapter gives an introduction to writing your first entity and session bean. You'll find that getting up and running is fairly simple.
Let's start by examining how to create an entity bean. We'll implement the Cabin entity that is part of the Titan Cruises Java EE application. The Cabin entity encapsulates the data and behavior associated with a cruise ship cabin in Titan's business domain. Although you can interact with entity beans outside of an application server, we will later create a TravelAgent session bean to serve as a data access interface for creating and locating cabins.
When developing an entity bean, all we need to define is the bean class. Entities in Java Persistence are plain Java objects that are annotated with O/R mapping metadata. We started to define the Cabin entity in Chapter 2; here, we add two new methods for setting and getting the ship ID and the bed count. The ship ID identifies the ship to which the cabin belongs, and the bed count tells how many people the cabin can accommodate:
package com.titan.domain

import javax.persistence.*;

@Entity
@Table(name="CABIN")
public class Cabin implements java.io.Serializable{
    private int id;
    private String name;
    private int deckLevel;
    private int shipId;
    private int bedCount;

    @Id
    @Column(name="ID")
    public int getId( ) { return id; }
    public void setId(int pk) { id = pk; }

    @Column(name="NAME")
    public String getName( ) { return name; }
    public void setName(String str) {name = str; }

    @Column(name="DECK_LEVEL")
    public int getDeckLevel( ) { return deckLevel; }
    public void setDeckLevel(int level) { deckLevel = level; }

    @Column(name="SHIP_ID")
    public int getShipId( ) { return shipId; }
    public void setShipId(int sid) { shipId = sid; }

    @Column(name="BED_COUNT")
    public int getBedCount( ) { return bedCount; }
    public void setBedCount(int bed) { bedCount = bed; }

}
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Developing an Entity Bean
Let's start by examining how to create an entity bean. We'll implement the Cabin entity that is part of the Titan Cruises Java EE application. The Cabin entity encapsulates the data and behavior associated with a cruise ship cabin in Titan's business domain. Although you can interact with entity beans outside of an application server, we will later create a TravelAgent session bean to serve as a data access interface for creating and locating cabins.
When developing an entity bean, all we need to define is the bean class. Entities in Java Persistence are plain Java objects that are annotated with O/R mapping metadata. We started to define the Cabin entity in Chapter 2; here, we add two new methods for setting and getting the ship ID and the bed count. The ship ID identifies the ship to which the cabin belongs, and the bed count tells how many people the cabin can accommodate:
package com.titan.domain

import javax.persistence.*;

@Entity
@Table(name="CABIN")
public class Cabin implements java.io.Serializable{
    private int id;
    private String name;
    private int deckLevel;
    private int shipId;
    private int bedCount;

    @Id
    @Column(name="ID")
    public int getId( ) { return id; }
    public void setId(int pk) { id = pk; }

    @Column(name="NAME")
    public String getName( ) { return name; }
    public void setName(String str) {name = str; }

    @Column(name="DECK_LEVEL")
    public int getDeckLevel( ) { return deckLevel; }
    public void setDeckLevel(int level) { deckLevel = level; }

    @Column(name="SHIP_ID")
    public int getShipId( ) { return shipId; }
    public void setShipId(int sid) { shipId = sid; }

    @Column(name="BED_COUNT")
    public int getBedCount( ) { return bedCount; }
    public void setBedCount(int bed) { bedCount = bed; }

}
The Cabin bean class is annotated with @javax.persistence.Entity and @javax.persistence.Table . The @Entity annotation tells the persistence provider that this is an entity class that is mapped to a database and that can be managed by an
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Developing a Session Bean
Now that our Cabin entity is ready, we need to create a session bean that will act as the interface for interacting with the Cabin entity. This session bean will take on the business process and responsibilities of a travel agent and will be called the TravelAgent EJB.
The first part of creating the TravelAgent EJB is to define its remote interface. This interface specifies what business methods a client is allowed to invoke on the EJB. Clients interact with the TravelAgent's createCabin( ) and findCabin( ) methods to manipulate Cabin entities:
package com.titan.travelagent;

import javax.ejb.Remote;
import com.titan.domain.Cabin;

@Remote
public interface TravelAgentRemote {

    public void createCabin(Cabin cabin);
    public Cabin findCabin(int id);
}
There really is nothing special about the remote interface of the TravelAgent EJB. It looks like a plain Java interface, except that it is annotated with the @javax.ejb.Remote annotation. This annotation tells the EJB container that this particular interface is the remote business interface of the TravelAgent EJB. Unlike EJB 2.1, also notice that the business methods do not have to throw java.rmi.RemoteException . They can if they want to, but they don't have to.
Now that we have defined the remote interface to the TravelAgent EJB, we need to implement the bean class that contains the business logic for this session bean. The TravelAgent EJB is defined as a stateless bean. We use the @javax.ejb.Stateless annotation to denote this. Although they are not required to, it is good practice for stateless session beans to implement all of their business interfaces so that the client/bean contract can be enforced by the Java compiler. In this case, the business interface is TravelAgentRemote . Here is the complete definition of the TravelAgentBean class:
package com.titan.travelagent;

import javax.ejb.Stateless;
import javax.persistence.EntityManager; 

import javax.persistence.PersistenceContext;

import com.titan.domain.Cabin;

@Stateless
public class TravelAgentBean implements TravelAgentRemote{
    @PersistenceContext 
(unitName="titan")
private EntityManager manager;

    public void createCabin(Cabin cabin) {
        manager.persist(cabin);
    }

    public Cabin findCabin(int pKey) {
       return manager.find(Cabin.class, pKey);
    }
}
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: Persistence: EntityManager
Persistence is a key piece of the Java EE platform. In older versions of Java EE, the EJB specification was responsible for defining this layer. In Java EE 5, persistence has been spun off into its own specification: Java Persistence 1.0. Persistence provides an ease-of-use abstraction on top of JDBC so that your code can be isolated from database, vendor-specific peculiarities and optimizations. It can also be described as an object-to-relational mapping engine (ORM). This means that the Java Persistence API can automatically map your Java objects to and from a relational database. In addition to object mappings, this service also provides a query language that is very SQL-like but is tailored to work with Java objects rather than a relational schema.
chapter-4 showed how to create and interact with an entity bean. For those of you familiar with the older EJB 2.x model for entity beans, you may have noticed that entity beans no longer have a Home interface. So, how are entity beans created? How are they updated and removed? How can you perform queries and such? All of these persistent actions are now performed through the javax.persistence.EntityManager service.
In the new Java Persistence specification, the EntityManager is the central service for all persistence actions. Entities are plain Java objects that are allocated just like any other Java object. They do not become persistent until your code explicitly interacts with the EntityManager to make them persistent. The EntityManager manages the O/R mapping between a fixed set of entity classes and an underlying data source. It provides APIs for creating queries, finding objects, synchronizing objects, and inserting objects into the database. It also can provide caching and manage the interaction between an entity and transactional services in a Java EE environment such as JTA. The EntityManager is tightly integrated with Java EE and EJB but is not limited to this environment; it can be used in plain Java programs.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Entities Are POJOs
Entities, in the Java Persistence specification, are plain old Java objects (POJOs). You allocate them with the new( ) operator just as you would any other plain Java object. Instances of an entity bean class do not become persistent until they are associated with an EntityManager. For instance, let's look at a simple example of a Customer entity:
import javax.persistence.*;

@Entity
public class Customer {
   private int id;
   private String name;

   @Id @GeneratedValue
   public int getId( ) {
      return id;
   }
   public void setId(int id) {
      this.id = id;
   }

   String getName( ) {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }
}
If we allocate instances of this Customer class, no magic happens when new( ) is invoked. Calling the new operator does not magically interact with some underlying service to create the Customer class in the database:
Customer cust = new Customer( );
cust.setName("Bill");
Allocated instances of the Customer class remain POJOs until you ask the EntityManager to create the entity in the database.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Managed Versus Unmanaged Entities
Before we can go any deeper into the entity manager service, we need to delve more deeply into the life cycle of entity object instances. An entity bean instance is either managed (a.k.a. attached) by an entity manager or unmanaged (a.k.a. detached). When an entity is attached to an EntityManager, the manager tracks state changes to the entity and synchronizes those changes to the database whenever the entity manager decides to flush its state. When an entity is detached, it is unmanaged. Any state changes to an entity that is detached are not tracked by the entity manager.
A persistence context is a set of managed entity object instances. Persistence contexts are managed by an entity manager. The entity manager tracks all entity objects within a persistence context for changes and updates made, and flushes these changes to the database using the flush mode rules discussed later in this chapter. Once a persistence context is closed, all managed entity object instances become detached and are no longer managed. Once an object is detached from a persistence context, it can no longer be managed by an entity manager, and any state changes to this object instance will not be synchronized with the database.
When a persistence context is closed, all managed entity objects become detached and are unmanaged.
There are two types of persistence contexts: transaction-scoped and extended persistence contexts.

Section 5.2.1.1: Transaction-scoped persistence context

Persistence contexts may live as long as a transaction and be closed when a transaction completes. This is called a transaction-scoped persistence context . When the transaction completes, the transaction-scoped persistence context will be destroyed and all managed entity object instances will become detached. Only application server managed persistence contexts can be transaction-scoped. In other words, only EntityManager instances injected with the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Packaging a Persistence Unit
An EntityManager maps a fixed set of classes to a particular database. This set of classes is called a persistence unit . Before you can even think about creating or querying entities with an entity manager, you must learn how to package a persistence unit for use within a Java SE (regular Java application) or Java EE (application server) environment. A persistence unit is defined in a persistence.xml file. This file is a required deployment descriptor for the Java Persistence specification. A persistence.xml file can define one or more persistence units. This file is located in the META-INF directory of:
  • A plain JAR file within the classpath of a regular Java SE program.
  • An EJB-JAR file. A persistence unit can be included with an EJB deployment.
  • A JAR file in the WEB-INF/lib directory in a web archive file (.war). See chapter-20 for details on what a WAR file is.
  • A JAR file in the root of an enterprise archive (.ear). See chapter-20 for details on what an EAR file is.
  • A JAR file in the EAR lib directory.
Figure 5-1 shows what the structure of one of these JAR files might look like.
Figure 5-1: titan-persistence.jar
The persistence.xml deployment descriptor defines the identities and configuration properties of each persistence unit described within it. Each persistence unit must have an identity, although the empty string is a valid name.
The set of classes that belong to the persistence unit can be specified, or you can opt for the persistence provider to scan the JAR file automatically for the set of classes to deploy as entities. When scanning is used, the persistence provider will look at every class file within the JAR to determine if it is annotated with the @javax.persistence.Entity annotation and, if it is, it will add it to the set of entities that must be mapped.
Each persistence unit is tied to one and only one data source. In Java SE environments, vendor-specific configuration must be used to define and configure these data sources. In Java EE environments, specific XML elements define this association.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Obtaining an EntityManager
Now that you have packaged and deployed your persistence units, you need to obtain access to an EntityManager so that you can persist, update, remove, and query your entity beans within your databases. In Java SE, entity managers are created using a javax.persistence.EntityManagerFactory . Although you can use the factory interface in Java EE, this platform provides some additional features that make it easier and less verbose to manage entity manager instances.
EntityManagers may be created or obtained from an EntityManagerFactory. In a Java SE application, you must use an EntityManagerFactory to create instances of an EntityManager. Using the factory isn't a requirement in Java EE.
package javax.persistence;

public interface EntityManagerFactory {
   EntityManager createEntityManager( );
   EntityManager createEntityManager(java.util.Map map);
   void close( );
   boolean isOpen( );
}
The createEntityManager( ) methods return EntityManager instances that manage a distinct extended persistence context. You can pass in a java.util.Map parameter to override or extend any provider-specific properties you did not declare in your persistence.xml file. When you are finished using the EntityManagerFactory, you should close( ) it (unless it is injected; ee'll discuss this later). The isOpen( ) method allows you to check to see if the EntityManagerFactory reference is still valid.

Section 5.4.1.1: Getting an EntityManagerFactory in Java SE

In Java SE, the javax.persistence.Persistence class is responsible for bootstrapping an EntityManagerFactory:
public class Persistence {
   public static EntityManagerFactory createEntityManagerFactory(
           String unitName
   );
   public static EntityManagerFactory createEntityManagerFactory(
           String unitName,
           java.util.Map 
 properties
   );
The javax.persistence.Persistence class looks for persistence.xml deployment descriptors within your Java classpath. The
Additional content appearin