image
CERTIFICATION OBJECTIVES
5.01  Identify the Correct EJB Technology to Apply for a Given Scenario, Including Entity Classes, Session Beans, Message-Driven Beans, Timers, Interceptors, and POJOs
5.02  Identify Benefits and Drawbacks of Different Persistence Technologies such as BMP, CMP, and JPA, Including Ease of Development, Performance, Scalability, Extensibility, and Security
5.03  Identify the Benefits and Drawbacks of Implementing Web Services in the EJB Component Container
5.04  Select the Appropriate Use of JPA and JPQL in a Given Scenario
imageTwo-Minute Drill
Q&A Self Test
The business tier contains the code that solves the needs of a business area, such as insurance, banking, retail, or finance. In a Java EE environment, business functionality is typically placed within enterprise beans running in the business tier (in some cases enterprise beans run in the web tier). An enterprise bean receives data from a client program, performs any necessary processing, and then sends data to a storage tier, such as a database or an enterprise information system tier. An enterprise bean can also receive data from a client program, retrieve data from a storage tier, perform any necessary processing, and then send it back to the client program. Figure 5-1 depicts the client, business, and persistence tiers of a Java EE application.
FIGURE 5-1  Java EE overview
image
Background on New Features in Java EE 6
The exam focuses less, if at all, on prior releases of Java EE and essentially concentrates on the new features of Java EE 6. In general, the design goals for this Java EE 6 are:
image Provide the foundation for the various components that make up the Java EE platform.
image Focus and improve development productivity, as follows:
image Add many new annotations.
image Reduce, or eliminate, the need for XML configuration.
image Move away from complex classes that implement interfaces and increase the ability to use Plain Old Java Objects (POJOs).
Java EE 6 continues the direction set by the Java EE 5 release, which can be summarized as follows:
image Utilize features supported by Java SE 5 (annotations, generics, type safe enums), making Java EE more declarative.
image Decouple EJBs from infrastructure.
image Add persistence for POJOs.
image Make code placed in business methods not required to declare checked exceptions.
image Make more of the deployment descriptors optional.
Java EE 6 also embraced many values that existed in complementary and competing frameworks. This brings forth a much cleaner and lighter framework with features, such as the following:
imageContexts and dependency injection (CDI) Looser coupling, scoping for components.
imageDependency injection Easier lookups. Declare external resources in code.
imageConvention over configuration Also known as “configuration by exception.” Simplifies decisions for the developer.
imageSimplified packaging
Table 5-1 provides the details for the new features of enterprise beans (EJB) 3.1.
TABLE 5-1  New Features for Enterprise Beans (EJB)
image
CERTIFICATION OBJECTIVE 5.01
Identify the Correct EJB Technology to Apply for a Given Scenario, Including Entity Classes, Session Beans, Message-Driven Beans, Timers, Interceptors, and POJOs
This section covers the enterprise bean (EJB) technology in Java EE. This includes describing the enterprise bean (EJB) technology that is appropriate for given scenarios.
Enterprise Bean Overview
A enterprise bean (or EJB) is a server-side component that contains business logic for an application. Enterprise beans contain fields (variables) and methods (functions) to implement business logic or functionality. Enterprise beans simplify the development of large, distributed applications, as follows:
image The enterprise bean (EJB) container provides system-level services to enterprise beans, such as security and transaction management, leaving the bean developer to focus on implementing the code to solve the business requirements.
image An enterprise bean (EJB) contains an application’s business logic, leaving the developer of a client application to focus on the presentation of the client. When the client application contains less code, there are fewer opportunities for defects, and a smaller client code footprint can be an important consideration for smaller devices.
image Provided that it uses the standard APIs, an enterprise bean (EJB) is a portable component and will run on any compliant Java EE container.
image
With the simplification and streamlining aspects of the EJB 3.1 release, enterprise beans can be placed in a web application archive (.war) file alongside web tier components. In other words, enterprise beans do not have to be contained in a separate ejb-jar file. The ejb-jar.xml file is optionally required and can be packaged as part of the .war file (/WEB-INF/folder).
Exam Scenarios to Utilize Enterprise Beans
For the exam, the use of enterprise beans is the most appropriate implementation for the following scenarios:
imageScalability To accommodate growing numbers of users, Java EE servers can be clustered (multiple machines), and enterprise beans of a deployed application will run on multiple members of the cluster.
imageTransactions Transactions ensure data integrity; the performance of an operation that changes data from a known state to another known state. Enterprise beans support transactions, the mechanisms that manage the concurrent access of shared objects.
imageFine-grained security Enterprise beans support declarative and programmatic, fine-grained security.
imageReuse Involves using business logic (functionality) from multiple types of clients (Web Start, Applet, web browser). With minimal code, a client can easily locate and utilize enterprise beans.
image
Exam Watch: Since the release of Java EE 5, the use of EJB entity beans has been discouraged and essentially replaced by entity classes using the Java Persistence API (JPA).
As mentioned earlier, the enterprise bean solely implements business logic, and all low-level system services are taken care of by the EJB container. Enterprise bean technology comes in three high-level types: entity class, session bean, and message-driven bean. We cover each of these types in detail as well as the scheduling timer service and the Aspect Oriented Programming (AOP) interceptor features.
Entity Class
An entity class is a lightweight persistence domain object. For the most part, an instance of an entity class will represent a row in a table or view in a relational database. The state of an entity is represented either through fields or properties. These fields or properties use Object Relational Mapping (ORM) annotations to map an entity and its relationships to the relational data in the persistence data store. All entity classes must abide by the following:
image They must be annotated with @Entity.
image They must have a public or protected, no-argument constructor.
image The class must not be declared final.
image The methods or persistent instance variables must not be declared final.
image (Optional) They must implement the Serializable interface if they are parameters (such as via a stateless session beans remote interface).
Plain Old Java Object (POJO)
The release of EJB 3 vastly simplified the way a developer builds classes to represent entities in a persistence layer (for example, database tables). A Plain Old Java Object, or POJO, is all that is needed (along with the new EJB3 annotations and transaction management) to be used in an Enterprise application.
Entity Bean
Entity beans are a legacy from the EJB spec prior to EJB 3. Since Java EE 5 was released, the use of entity beans has been discouraged and essentially replaced by entity classes using the Java Persistence API (JPA). Like EJB 3 entity classes, entity beans are used in pre-Java EE 5 platform implementations in the following areas:
image To represent persistent data in an object with a clearly defined identity
image To provide secure, concurrent access to multiple clients
image To provide robust, long-lived persistent data management
image To provide access through query language (EJB-QL) for container-managed persistence (CMP) and SQL for bean-managed persistence (BMP)
image To provide simplified transaction handling
As mentioned previously, an entity bean can implement either bean-managed persistence (BMP) or container-managed persistence (CMP). In the case of BMP, the implementer of an entity bean stores and retrieves the information managed by the bean through direct database calls. One disadvantage to this approach is that it makes it more difficult to adapt BMP entity beans to alternative data sources. In the case of CMP, the container provider may implement access to the database using standard APIs. The container provider can offer tools to map instance variables of an entity bean to calls to an underlying database. This approach makes it easier to use CMP entity beans with different databases.
Look at the coverage for the exam objective that covers CMP and BMP later in this chapter for more information on EJB entity beans.
Session Bean
A session bean is an enterprise bean that contains business logic that implements a process or specific functionality (and/or workflow). A session bean would be the right type of enterprise bean to be used in the following scenarios:
image When only one client has access to the bean instance at any given time
image If the enterprise bean’s state does not need to be persisted
image If the enterprise bean is implementing a web service
Session beans come in three subtypes: stateless, stateful, and singleton. Let’s look at each of these subtypes.
Stateless Session Bean (SLSB)
A stateless session bean does not maintain a conversational state with the client. When a client invokes the methods of a stateless bean, the bean’s instance variables may contain a state specific to that client, but only for the duration of the invocation. When the method is finished, the client-specific state should not be retained. Clients may, however, change the state of instance variables in pooled stateless beans, and this state is held over to the next invocation of the pooled stateless bean. Except during method invocation, all instances of a stateless bean are equivalent, allowing the container to assign an instance to any client. That is, the state of a stateless session bean should apply across all clients. Because stateless session beans can support multiple clients, they can offer better scalability for applications that require large numbers of clients. Typically, an application requires fewer stateless session beans than stateful session beans to support the same number of clients.
A stateless session bean can implement a web service, but other types of enterprise beans cannot.
image
Use a stateless session bean in the following scenarios:
imageThe bean’s state has no data for a specific client.
imageThe bean performs a task for any client during a single method invocation.
imageTo implement a web service endpoint.
Stateful Session Bean (SFSB)
In a stateful session bean, the instance variables represent the state of a specific client/bean session, and this state is available for the duration of the client/bean session. The session and its state ends when the client removes the bean or when the client terminates.
image
Use a stateful session bean for any of the following situations:
imageThe bean’s state represents the interaction between the bean and a specific client.
imageThe bean needs to hold information about the client access method invocations.
imageThe bean mediates between the client and the other components of the application, presenting a simplified view to the client.
Singleton Session Bean (SSB)
A singleton session bean follows the namesake design pattern and is instantiated once per application (per Java Virtual Machine) and then exists until the application is stopped. The purpose of the singleton session bean is to maintain session state and to provide functionality that can be accessed concurrently by clients (until the application is stopped, or the server crashes or is shut down).
Applications that use a singleton session bean may specify that the singleton should be instantiated upon application startup, which allows the singleton to perform initialization tasks for the application. The singleton may perform cleanup tasks on application shutdown as well, because the singleton will operate throughout the life cycle of the application.
image
Use a singleton session bean in the following situations:
imageThe state or functionality needs to be shared (accessed by multiple threads concurrently) across an application.
imageThe application needs to perform tasks at startup and/or during shutdown.
imageThe bean implements a web service endpoint.
There are two choices for controlling concurrency for a singleton session bean:
imageContainer-managed concurrency (CMC) The Java EE container controls access to a singleton session bean instance based on method-level locking metadata. Annotate a singleton bean with @ConcurrencyManagement (Concurrency ManagementType.CONTAINER).
imageBean-managed concurrency (BMC) The Java EE container permits full concurrent access to a singleton session bean instance and defers state synchronization to code within the singleton session bean instance. Annotate a singleton bean with @ConcurrencyManagement (ConcurrencyManagementType.BEAN).
Message-Driven Bean (MDB)
A message-driven bean (MDB) is an enterprise bean that allows a Java EE application to process messages in an asynchronous way, as opposed to session beans, which allow you to send JMS messages and to receive them synchronously. MDBs typically process JMS messages by acting as a JMS message consumer, but they can consume messages from other providers—for example, Java Connector Architecture (JCA). Messages can be inserted into a JMS Topic or JMS Queue from many sources, including other Java EE components, but a message can also be inserted from non-Java EE components. All instances of an MDB are equivalent and the Java EE container can pool these instances, in a manner similar to stateless session bean, to allow streams of messages to be processed simultaneously. MDBs have the following characteristics:
image They are stateless, but they can access and update shared data in a database.
image They execute upon receipt of a message from a client.
image They are invoked asynchronously.
image They execute for short periods.
image They can be made part of a transaction (redelivered upon rollback).
When a message arrives, the container calls the message-driven beans onMessage method to process the message. The onMessage method normally casts the message to one of the five JMS message types and handles it in accordance with the application’s business logic.
image
Use a message-driven bean in the following situations:
imageFor long-running tasks to be processed asynchronously
imageWhen resources are not always available
imageIf you want to parallelize processing
imageTo receive and process messages from third-party applications
Timer Service
The timer service of the enterprise bean container enables you to schedule timed notifications for all types of enterprise beans (except for stateful session beans). You can schedule a timed notification to occur according to a calendar schedule, at a specific time, after a duration of time, or at timed intervals. There are two types of timers:
imageProgrammatic Set by explicitly calling one of the timer-creation methods of the TimerService interface. When a programmatic timer expires, the container calls the method that is annotated with @Timeout in the bean’s implementation class. This method has the business logic for such timed events.
imageAutomatic Created upon the successful deployment of an enterprise bean that contains a method annotated with the java.ejb.Schedule or java.ejb.Schedules annotation.
Interceptors (AOP)
Interceptors are the implementation of aspect-oriented programming (AOP) features in Java EE. AOP is a programming approach that increases modularity by separation of cross-cutting concerns. In Java EE, interceptors allow developers to invoke interceptor methods on an associated target class, in conjunction with method invocations or when life cycle events (bean creation/destruction) occur. Common uses of interceptors are typical cross-cutting concerns such as logging, auditing, and profiling, but they can also be used to extend functionality to existing classes for which you do not have source code (for example, a third-party product).
An interceptor can be defined within a target class as an interceptor method, or in an associated class called an interceptor class. Interceptor classes contain methods that are invoked in conjunction with the methods or life cycle events of the target class. Interceptor classes and methods are defined using metadata annotations, or in the deployment descriptor of the application containing the interceptors and target classes.
image
Use an interceptor to extend functionality. The interceptor is invoked when business methods on the target class are invoked. Any object managed by Java EE can have an interceptor associated with it.
The following scenario and solutions table shows the appropriate EJB technology for a list of scenarios.
SCENARIO & SOLUTION
Given Scenario
Appropriate EJB Technology
To represent data being retrieved from, and saved to, a persistence layer (for example, relational database)
Entity classes. (You will have to consider entity beans if you are extending the functionality of an existing EJB 2.x implementation.)
If you do not have to store state data for a specific client
To perform business functionality for any client during a single method invocation
To implement a web service endpoint
Stateless session bean (SLSB).
To represent state (or information) for a specific client
To present a simplified view of a mediation between client and several server-side components of an application
Stateful session bean (SFSB).
If state (or functionality) needs to be shared across an application (internally) or via a web service end point (externally)
To perform tasks at application startup and/or during shutdown
Singleton session bean (SSB).
To integrate with a third-party application where messages are received via JMS
For long-running tasks to be processed asynchronously
When resources are not always available
If you want to parallelize processing
Message-driven bean (MDB).
CERTIFICATION OBJECTIVE 5.02
Identify Benefits and Drawbacks of Different Persistence Technologies such as BMP, CMP, and JPA, Including Ease of Development, Performance, Scalability, Extensibility, and Security
Several persistence technologies are available in Java EE that you must be familiar with in order to pass the exam.
Gauging Benefits and Drawbacks
Before we cover the persistence technologies, let’s take a quick look at the nonfunctional requirements and qualities that are typically used to gauge the benefits and drawbacks of these persistence technologies.
Ease of Development
Ease of development typically refers to qualities that make developers more productive and able to implement more functionality in a shorter periods of time with simple or straightforward approaches. For Java EE specifically, we can look at examples of this with features such as annotations, which can be used to define and wire functionality along with the code instead of separately in configuration files. Another example is JPA, where persistence details are left up to the JPA implementation to deal with leaving the developer free from having to explicitly write SQL code, thus reducing development time.
The older EJB (2.x and prior) specification releases required significantly more overhead and implementation work by the developer. There was a big push in the EJB 3.0 specification, and continuing with EJB 3.1, to vastly simplify the process of developing EJBs of all types and thus improve developer productivity.
Performance
In terms of persistence and performance, there is typically a tradeoff in having the details of the persistence being delegated to a container or specific persistence implementation or having a developer implement the persistence details in code.
Examples of persistence delegation are JPA-based EJB 3.x entity classes and EJB 2.x CMP entity beans. In general, there is the potential for a run-time performance penalty to be paid for the productivity gains realized during development and ongoing maintenance. A contrasting example is where the developer takes more time and effort to implement SQL calls via JDBC, potentially producing the fastest possible performance in all or at least most test cases.
image
It is possible for delegated persistence approaches to be tuned to the point where they can be comparable to or even outperform developer-coded persistence. Persistence container services can be configured to incorporate caching and pre-fetching approaches, thus reducing the number of expensive I/O or network calls. In short, mileage can vary—there is no one clear winner just yet.
Scalability
In terms of the persistence approach to scalability, the EJB container has the ability to manage a pool of enterprise beans. The underlying Java EE servers have configuration properties for sizing and managing these bean pools. These properties can be set by taking into account the number, frequency, and duration of client requests. Here are some general rules of thumb:
image Stateless session beans are the most scalable because the container can reuse the bean instance after each method invocation.
image Stateful session beans are less scalable because the container must map one bean instance for every concurrent client until the client session is completed.
Extensibility
As additional functionality is added to an existing application, when it comes to a particular persistence approach, there are no clear advantages (or disadvantages) to either delegated persistence or explicitly coded persistence. In the case of a relational database table having additional columns, regardless of persistence approach, the additional effort is needed to meet the new requirements. The ease of extensibility has no clear winner.
Security
Again, no clear benefits or drawbacks among differing persistence strategies because security has always been one of the core feature of enterprise beans and the EJB container.
So now we have briefly covered the nonfunctional requirements and qualities that are typically used to gauge the benefits and drawbacks of these persistence technologies. We will now cover each of the persistence approaches in more detail before showing a comparison of the benefits and drawbacks of each.
Bean-Managed Persistence (BMP)
When using bean-managed persistence (BMP) entity beans, developers are required to implement code to save the state of the bean to the underlying persistence layer. This does provide the developer with exact control of the way the persistence takes place and often results in the improved performance over CMP implementations, but it comes with the overhead of an increasing amount of potentially more complicated code (increase in complexity not always the case, though). BMP is best suited for specific scenarios where CMP cannot deliver the performance or the underlying persistence layer is not supported by CMP.
The benefits of using bean-managed persistence include the following:
imageStandards based The standard EJB and JDBC APIs can be used for data access calls.
imageData type access The ability to access nonstandard data types and legacy applications is supported.
imageMaximum flexibility Data validation logic of any complexity is supported.
imageDatabase specific features The application is able to take advantage of nonstandard SQL features of different SQL servers.
The drawbacks to using bean-managed persistence include the following:
imageDatabase specific Because entity bean code is database specific, if access to multiple databases is required, the enterprise bean provider will have to account for this in its data access methods.
imageKnowledge of SQL The enterprise bean provider must have knowledge of SQL.
imageDevelopment time These beans on average take a much longer time to develop.
Container-Managed Persistence (CMP)
When using container-managed persistence (CMP), entity beans leave the persistence of their state to the EJB container. This simplifies the amount of code that needs to be implemented, thus increasing the productivity of the developer. However, the SQL that is generated and submitted to the database server may not be optimal. Knowledge of SQL and the underlying database schema is still essential for the developer, if only to debug and troubleshoot the SQL the CMP implementation is issuing.
The benefits of using container-managed persistence include the following:
imageDatabase independence The container, not the enterprise bean provider, maintains database access code to most popular databases.
imageContainer-specific features Features such as full text search are available for use by the enterprise bean provider.
imagePortability Portability to other EJB containers is straightforward but does not guarantee the same performance.
The drawbacks to container-managed persistence include the following:
imageAlgorithms Only container-supported algorithms persistence can be used.
imageAccess The developer has no access to the view and cannot modify the actual code.
imageEfficiency Sometimes the generated SQL is not the most efficient with respect to performance.
Java Data Objects (JDO)
The Java Data Objects (JDO) API is a standard interface-based Java model abstraction of persistence, developed under the auspices of the Java Community Process. A developer can use JDO to store Java domain model instances into the persistent store.
The benefits of using JDO are:
imageEase of use The developer focuses on the domain object model; the persistence details are taken care of by the JDO implementation.
imagePortability JDO applications run on several JDO implementations without change. Also, JDO supports a large number of relationship and data types, and it has no proxy objects.
imageDatabase independence JDO applications are independent of the underlying data store. The transactional data stores are not limited to relational databases; there is also support for NoSQL data sources, object databases, XML, flat files, and other persistence tiers. It is also possible to more easily switch from a SQL to a NoSQL data source, and vice versa.
imageHigh performance The persistence details are taken care of by the JDO implementation, so there is an opportunity to obtain optimal performance through optimized data access patterns.
imageIntegration with EJB JDO applications can still take advantage of the major EJB features using the same domain object models—features such as transaction coordination, security, and remote message processing.
The main drawback of using JDO is that it is not as frequently updated.
Java Database Connectivity (JDBC)
The Java Database Connectivity (JDBC) API lets you invoke SQL commands from Java programming language methods. You use the JDBC API within multiple Java EE components (enterprise beans, servlets, and JSP) to access the database directly without using entity beans or entity classes. The JDBC API has two parts: an application-level interface used by the application components to access a database, and a service provider interface to attach a JDBC driver to the Java EE platform.
The benefits of using JDBC include the following:
image It is easy to test.
image It is platform independent.
image It offers the potential to maximize query performance.
The drawbacks of using JDBC include the following:
image The developer needs to code and handle all checked exceptions.
image There is no support for relationships, inheritance, and associations.
image Implementation is up to the developer.
image The developer needs to know SQL and relational model.
Java Persistence API (JPA)
The Java Persistence API (JPA) was introduced by the Java EE 5 specification and has been steadily enhanced. Its purpose is to simplify and standardize the approach to mapping Java objects to relational database tables, more commonly known as Object Relational Mapping (ORM). JPA also simplifies the programming model for entity persistence and adds capabilities that were not in EJB 2.1. JPA establishes standards for mapping entities to relational tables and creating the ORM configuration metadata. The EntityManager API exposes operations that INSERT, SELECT, UPDATE, and DELETE entities, where entities are persistence objects that model persistent data stored in a relational database. However, there are some cases where JPA is not recommended or possible, and we will cover those scenarios next.
The benefits of using JPA include the following:
image It can be used outside of the container and therefore is also easier to test.
image It can be used with pluggable, third-party persistence providers (Hibernate, TopLink, OpenJPA).
image It offers cleaner, easier, standardized Object Relational Mapping. In particular:
image It eliminates the need for lookup code (annotations drive this).
image It reduces or eliminates deployment descriptor entries (it use annotations instead).
image It requires fewer classes and interfaces.
image Java Persistence Query Language (JPQL), an enhanced EJB QL, can be used to search through and retrieve data.
The drawbacks of using JPA include the following:
image There is the potential for suboptimal performance. The generated SQL statements may not perform as needed because of the data store design and implementation.
image If the existing implementation is not using JPA and you need to extend functionality in a minor way, a rewrite of the entire tier to use JPA is typically not permitted or justified (large cost and increased risk).
image If the underlying persistence layer is not supported sufficiently by the JPA implementation. This situation occurs mostly when the persistence layer is not one of the major relational databases.
Comparing Persistence Types
Table 5-2 shows the benefits and drawbacks of each of the persistence types found for Java EE.
TABLE 5-2  Benefits and Drawbacks of Java EE Persistence Technology
image
CERTIFICATION OBJECTIVE 5.03
Identify the Benefits and Drawbacks of Implementing Web Services in the EJB Component Container
For this objective we examine the advantages and disadvantages to implementing web services within the EJB container. We look at exposing enterprise beans as web services as well as calling web services from enterprise beans.
Web Services
Before looking at how enterprise beans (EJBs) can be exposed as web service end points and how they can call web services to consume data, we will first quickly review the web services available in the Java EE platform.
Java API for XML Web Services (JAX-WS)
JAX-WS is a technology for building web services and clients that communicate using XML. It defines the core specification for the web services standard in Java EE. It provides a way for the developer to expose singleton and stateless session beans (as well as other POJOs) as web services.
Java API for RESTful Web Services (JAX-RS)
JAX-RS provides support for web services that conform to the Representational State Transfer (REST) architectural pattern. It also provides a way for the developer to expose singleton and stateless session beans (as well as other POJOs) as web services.
Enterprise Beans and Web Services
In the new releases of the Java EE platform, it has become fairly straightforward for an enterprise bean (EJB) to become either a provider or a consumer of web services. Adding the @WebService annotation to an enterprise bean (stateless and singleton session beans only) will expose all the public methods of the EJB as a web service when deployed. The Java EE platform publishes the public methods as web service operations, mapping the arguments for each operation into an XML schema. Likewise, an enterprise bean (EJB) can access web services using either of the Java Web Service APIs (JAX-WS and JAX-RS) listed earlier in this section.
The benefits of using enterprise beans (EJB) and web services include the following:
image Increased developer productivity to meet changing business requirements and needs.
image A provider is quickly able to expose business functionality as web services.
image A consumer is quickly able to build or modify an enterprise bean (EJB) so it can consume web services.
The drawbacks of using enterprise beans (EJB) and web services include the following:
image As a provider:
image Directly exposing business functionality instead of the preferred architectural approach of a well-defined and more centralized integration tier may be viewed as disorganized and somewhat messy.
image There is a security concern with data and functionality being directly available to external applications/clients. This points to weakness in the direct approach in place of the centralized integration tier mentioned earlier.
image As a consumer:
image If web service calls are added to an existing enterprise bean, then appropriate steps need to be taken to validate data being sent to the service and the data being received so that invalid data does not leak into the application or its persistence layer.
CERTIFICATION OBJECTIVE 5.04
Select the Appropriate Use of JPA and JPQL in a Given Scenario
For this objective we examine the scenarios for which JPA and JPQL are appropriate. Before covering the scenarios, we first quickly review the Java Persistence API and Java Persistence Query Language (JPQL) available in the Java EE platform. Figure 5-2 depicts an overview of the Java Persistence API for a Java EE application.
FIGURE 5-2  Java Persistence API (JPA) overview
image
Java Persistence API (JPA)
As mentioned earlier in this chapter, the Java Persistence API (JPA) greatly simplifies Java persistence and provides an Object Relational Mapping (ORM) approach that enables developers to define how to map Java objects (entities) to relational database tables in a standard, portable, and declarative (within code) way. These are known as JPA entities and are discussed next.
JPA Entities
A JPA entity is a Plain Old Java Object (POJO) that manages persistent data. There is no requirement to implement an interface (it is able to, though), and as such it is a lightweight object. A developer places annotations within the code to map the fields within an entity to columns in a database table.
Java Persistence Query Language (JPQL)
The Java Persistence Query Language allows a developer to define queries for entities and their persistent state. JPQL uses a SQL-like syntax to select objects based on entity abstract schema types and relationships that exist among them. In other words, JPQL can be considered as an object-oriented version of SQL.
The advantages of JPQL are:
image JPQL queries look similar to SQL queries, which can be familiar, easy to use, and simple to understand.
image For simple static queries, string-based JPQL queries (for example, as named queries) may be preferred.
Named Query
A JPA named query is a statically predefined unchangeable query string. Its primary goal is to create more efficient queries by forcing developers to use query parameters in place of embedding literals in a string. Named queries, defined by the @NamedQuery and @NamedQueries annotations, are also placed separately from the Java code that uses them, and the separation is considered an improvement to the organization of the code.
Given Scenario
Appropriate Use of JPA and JPQL?
The data model is simple, in terms of size and relationships, and the development team would like to start using an ORM approach to development.
Yes, JPA using JPQL and/or the JPA Criteria API is an appropriate fit for this scenario.
The development team is making minor updates to an existing EJB 2.x application.
No, existing EJB 2.x applications should keep to using CMP and/or BMP entity beans.
You are architecting a new Java EE application that persists data represented within Java objects to a relational database.
Yes, this is an appropriate scenario for using JPA and JPQL.
JPA Criteria API
A new feature introduced in JPA 2.0 is the JPA Criteria API, which allows a developer to dynamically build object-based queries instead of defining queries using Java Persistence Query Language (JPQL). Whereas JPQL queries are defined as strings (like SQL), JPA criteria queries are defined by instantiation of Java objects that represent query elements. Neither approach to queries has a power or efficiency advantage, so the choice comes down to the personal preference of the developer. The advantages of JPA Criteria API are:
image The Criteria API is a type-safe API, so type-checking errors will be detected during compilation instead of at run time.
image Mixing SQL strings throughout an application’s logic can surface issues. For example, some developers are not comfortable with SQL, or those that are may not create good SQL anyway. Use of the Criteria API will alleviate these issues.
image For dynamic queries that are built at run time, the Criteria API may be preferred instead of building queries using many string concatenation operations.
Table 5-3 shows the appropriate use of JPA and JPQL for given scenarios.
CERTIFICATION SUMMARY
By studying this chapter, you will have an understanding of the business tier technologies that will be tested on the exam.
 
image TWO-MINUTE DRILL
Identify the Correct EJB Technology to Apply for a Given Scenario, Including Entity Classes, Session Beans, Message-Driven Beans, Timers, Interceptors, and POJOs
image Use an entity class (EJB 3.x) to represent data being retrieved from, and saved to, a persistence layer (for example, relational database). Note: You will have to consider an entity bean if you are extending functionality of an existing EJB 2.x implementation.
image Use a stateless session bean (SLSB) for the following scenarios:
image You do not have to store state data for a specific client.
image To perform business functionality for any client during a single method invocation.
image To implement a web service end point.
image Use a stateful session bean (SFSB) for the following scenarios:
image To represent state (or information) for a specific client.
image To present a simplified view of a mediation between the client and several server-side components of an application.
image Use a singleton session bean (SSB) for the following scenarios:
image If state (or functionality) needs to be shared across an application (internally) or via a web service end point (externally).
image To perform tasks at application startup and/or during shutdown.
image Use a message-driven bean (MDB) for the following scenarios:
image To integrate with a third-party application where messages are received via JMS.
image For long-running tasks to be processed asynchronously.
image When resources are not always available.
image If you want to parallelize processing.
Identify Benefits and Drawbacks of Different Persistence Technologies such as BMP, CMP, and JPA, Including Ease of Development, Performance, Scalability, Extensibility, and Security
image The benefits to bean-managed persistence (BMP) are:
imageStandards based  Standard EJB and JDBC APIs for data access calls.
imageData type access  Support for nonstandard data types and legacy applications.
imageMaximum flexibility  Support for complex data validation logic. For exact control over the SQL being sent to the database or to implement code to match a specific legacy database schema. For example, if your persistent store is not a database system or is a legacy database system that is not supported by the EJB container’s CMP implementation.
imageDatabase-specific features  Can take advantage of nonstandard SQL features.
imagePerformance  If the query needs of the application exceed the capabilities of CMP or if the application needs fine-grained coding of SQL to perform effectively. However, it is recommended that data access objects (DAOs) be used. DAOs better enable the bean to be adapted to a different database schema or to evolve into a CMP entity bean later on.
imageBackward Compatibility  Better fit if you are extending an existing EJB 2.x BMP implementation.
image The drawbacks to bean-managed persistence (BMP) are:
imageDatabase specific  Entity bean code is database specific and less portable.
image Deeper knowledge of SQL is required.
imageDevelopment time  Takes longer time to develop.
image The benefits to container-managed persistence (CMP) are:
imageDatabase independence  Container handles persistence details.
imageContainer-specific features  Additional container features are available.
imagePortability  Very portable to other EJB containers.
image Better fit if you are extending an existing EJB 2.x CMP implementation.
image The drawbacks to container-managed persistence (CMP) are:
imageAlgorithms  Only container-supported algorithms are available.
imageAccess  No access to the view, and generated code cannot be modified.
imageEfficiency  Generated SQL may not perform as well as required.
image The benefits to Java Data Objects (JDO) are:
imageEase of use  Like JPA, the developer focuses on building the model and leaves persistence details to the JDO implementation.
imagePortability  JDO applications run on several JDO implementations without change.
imageDatabase independence  JDO applications are independent of the underlying data store. Support for SQL and NoSQL as well as other data store types.
imageHigh performance  JDO implementations have optimized data access patterns.
imageIntegration with EJB  JDO applications can also have EJB features: transaction coordination, security, and remote message processing.
image The drawbacks to Java Data Objects (JDO) are:
imageOlder code  Not as frequently updated.
image The benefits of using Java Database Connectivity (JDBC) are:
imageTesting  Easy to test components that use JDBC.
imageDatabase Agnostic  Platform independent.
imagePerformance  Potential to maximize query performance.
image The drawbacks of using Java Database Connectivity (JDBC) are:
imageExceptions  Need to code and handle all checked exceptions.
imageRelationships  No support for relationships, inheritance, and associations.
imageMore Coding  Implementation is up to the developer.
imageSQL Knowledge  Developer needs to know SQL and relational model.
image The benefits of using Java Persistence API (JPA) are:
imageTesting  Usable outside of the container and therefore also easier to test.
imagePlugins  Usable with pluggable, third-party persistence providers (Hibernate, TopLink, OpenJPA).
imageStandard  Cleaner, easier, standardized object-relational mapping:
image Eliminates the need for lookup code (annotations drive this).
image Reduces or eliminates deployment descriptor entries (use annotations instead).
image Requires fewer classes and interfaces.
imageJava Persistence Query Language (JPQL)  An enhanced EJB QL to search through and retrieve data.
imageCriteria API  Dynamically built object-based queries.
image The drawbacks of using Java Persistence API (JPA) are:
imagePotentially suboptimal performance  The generated SQL statements may not perform as needed because of the data store design and implementation.
imageIf existing implementation is not using JPA and you need to extend functionality in a minor way  In these types of cases, a rewrite of the entire tier to use JPA is typically not permitted or justified (due to large cost and increased risk).
imageIf the underlying persistence layer is not supported sufficiently by the JPA implementation  This situation occurs mostly when the persistence layer is not one of the major relational databases.
Identify the Benefits and Drawbacks of Implementing Web Services in the EJB Component Container
The benefit of using enterprise beans (EJB) and web services is:
image Increased developer productivity to meet changing business requirements and needs. It’s easy to expose EJB as a web service provider and to create or modify an EJB to consume web service(s).
The drawbacks of using enterprise beans (EJB) and web services include the following:
image Direct exposure as a web service provider is a security concern as well as being counter to the preferred architectural approach of a well-defined and more centralized integration tier.
image As web service calls are added to an enterprise bean (EJB), the developer must ensure the data being sent and received is valid to prevent invalidate data leaking into the application or its persistence layer.
Select the Appropriate Use of JPA and JPQL in a Given Scenario
image If you are architecting an new Java EE application that persists data represented within Java objects to a relational database, this is an appropriate scenario for using JPA and JPQL.
image If you are making minor updates to an existing EJB 2.x application, it is probably not a good scenario for using JPA and JPQL technology. It makes more sense to keep to using EJB 2.x CMP and/or BMP entity beans.
 
The following questions will help you measure your understanding of the material presented in this chapter. Read all the choices carefully because there may be more than one correct answer. Choose all correct answers for each question.
Identify the Correct EJB Technology to Apply for a Given Scenario, Including Entity Classes, Session Beans, Message-Driven Beans, Timers, Interceptors, and POJOs
1.  Serengeti Trading Company is starting to develop a new system that enables its participants, who reside anywhere around the world, to buy and sell items in an open auction fashion. Serengeti has a primary goal to ensure that all participants are treated absolutely equally in all respects; this includes dedicating resources to each participant so that they do not impact each other. Serengeti has sufficient funding to procure whatever is needed on the technology budget to achieve its goal. Which one of the following solutions do you recommend?
A. Stateless session beans (SLSB)
B. Stateful session beans (SFSB)
C. Message-driven beans (MDB)
D. BMP entity beans
2.  An application needs to read messages from a JMS queue, call a web service using data provided within the message, and persist data from the web service response in a database table. Which type of EJB will you use?
A. Stateful session bean (SFSB)
B. Stateless session bean (SLSB)
C. Message-driven bean (MDB)
D. Entity class
3.  If you are to follow the best practice for Java EE architecture, where would you place business rules and functionality?
A. Java servlets
B. Enterprise beans (EJB)
C. JAX-RS Web Services
D. JAX-WS Web Services
4.  Which of the following would you recommend for business logic for a highly available, complex transactional system?
A. Use session beans with JPA
B. Use JPA
C. Use a web-centric architecture
D. Use stateful session beans
5.  Which of the following EJB types should be avoided where possible if you are architecting an application for use by a very high number of users?
A. Entity bean
B. Message-driven bean (MDB)
C. Stateful session bean (SFSB)
D. Stateless session bean (SLSB)
Identify Benefits and Drawbacks of Different Persistence Technologies such as BMP, CMP, and JPA, Including Ease of Development, Performance, Scalability, Extensibility, and Security
6.  ABC Corp is a small B2C reverse-auctioneering online business. You have been asked to recommend a persistence strategy for their new platform, which is a green field (that is, no existing code or database schemas) project. Top priorities are ease of development and integration with EJB 3. What do you recommend?
A. JDBC
B. CMP entity beans
C. BMP entity beans
D. JPA
7.  Which of the following is not a benefit of JPA persistence technology?
A. Callable outside of the EJB container
B. Eliminates JNDI lookups
C. Utilizes POJOs
D. Works with NoSQL data sources
8.  Which of the following is not a benefit of CMP persistence technology?
A. Container generates SQL.
B. Can be switched to JPA later on.
C. Deeper knowledge of SQL is required.
D. Takes less time to develop.
9.  You have been brought into a company to recommend an approach to exposing some existing EJB-based business functionality to their external customers for a short period of time that is fast approaching. What do you recommend if security is not a consideration?
A. Expose an existing EJB as web service.
B. Create a JAX-WS web service that calls EJB.
C. Create a Java servlet that calls EJB.
D. Create a JSP that calls EJB.
10.  Which of the following is a drawback to calling web services from an EJB component?
A. Increased productivity.
B. Increased security.
C. It is counter to the preferred architectural approach.
D. It increases validity of data.
Select the Appropriate Use of JPA and JPQL in a Given Scenario
11.  An existing application uses EJB 2.0 CMP entity beans heavily. The application has no major issues in production, and little future development is planned. You have been asked to recommend a methodology to adopt when making minor modifications to the application. What do you recommend?
A. JPA entity classes
B. BMP entity beans
C. CMP entity beans
D. Use DAO accessing JDBC directly
12.  You are architecting an new Java EE application that persists data represented within Java objects to a relational database. Which of the following do you recommend?
A. JPA entity classes
B. BMP entity beans
C. CMP entity beans
D. Use DAO accessing JDBC directly
 
Identify the Correct EJB Technology to Apply for a Given Scenario, Including Entity Classes, Session Beans, Message-Driven Beans, Timers, Interceptors, and POJOs
1.imageB. Stateful session beans allow a Java EE application to access and retain resources for a user for the lifetime of their session.
imageA, C, and D are incorrect. These do not solve the core goal of dedicating resources for a user.
2.imageC. Message-driven bean reads from a JMS queue and initiates the work.
imageA, B, and D are incorrect. These other options do not asynchronously read from a JMS queue, but can be invoked by a message-driven bean (MDB) to execute the work needed.
3.imageB. Enterprise beans (EJB) are architecturally the “best practice” location for business rules and functionality.
imageA, C, and D are incorrect. Servlets and web services are architecturally not the best practice locations for business rules and functionality.
4.imageA. Session beans with JPA have the transactional support needed.
imageB, C, and D are incorrect. A web-centric approach does not fundamentally imply transactional support. JPA does not provide transactional support by itself. There is no mention for the need for stateful architecture, so stateful session beans are not needed.
5.imageC. The EJB container needs a stateful session bean instance for each concurrent user, so this type of resource-intensive bean should be avoided unless requirements make it absolutely necessary.
imageA, B, and D are incorrect. These bean types can be used in high-concurrent-user scenarios.
Identify Benefits and Drawbacks of Different Persistence Technologies such as BMP, CMP, and JPA, Including Ease of Development, Performance, Scalability, Extensibility, and Security
6.imageD. JPA offers the best integration with EJB 3 and has been designed with ease of development in mind.
imageA, B, and C are incorrect. These choices are certainly viable, but JPA still offers the best integration with EJB 3.
7.imageD. JPA does not work with NoSQL implementations.
imageA, B, and C are incorrect. They are all benefits of JPA, not drawbacks.
8.imageC. Deeper knowledge of SQL is not required (it may be useful, though).
imageA, B, and D are incorrect. They are all benefits of CMP, not drawbacks.
Identify the Benefits and Drawbacks of Implementing Web Services in the EJB Component Container
9.imageA. Exposing an existing EJB as a web service can be done quickly, and with security not being a consideration, this is the best choice.
imageB, C, and D are incorrect. Although B is not a wrong approach, the time pressure to deliver combined with security not being a consideration makes this a less-than-suitable approach. C and D do not expose a web service interface.
10.imageC. Calling a web service from an EJB component is considered running counter to the preferred architectural approach of using an integration tier.
imageA, B, and D are incorrect. These are not drawbacks.
Select the Appropriate Use of JPA and JPQL in a Given Scenario
11.imageC. Continuing to use EJB 2.0 CMP entity beans is the pragmatic approach.
imageA, B, and D are incorrect. These choices introduce significant new code that would need to be fully regression tested. For a very stable application that does not require very much new development, venturing into considerably more development is unwise.
12.imageA. Using JPA entity classes is the recommended approach for persisting Java objects in a relational database.
imageB, C, and D are incorrect. These choices, although not wrong, are not the best fit for the given scenario.