Design enterprise applications with JPA for EJB 3.0

Source: Internet
Author: User
Tags define final new features version variable jboss jboss application server access
Program | Design This article will introduce a design approach to Java Platform, Enterprise Edition (Java EE 5), which leverages Enterprise JavaBeans (EJB) 3.0 new Java Persistenc E API (JPA). JPA provides a standard object-relational mapping solution that avoids reliance on third-party frameworks such as Hibernate. You will see the details of the sample application, which validates the method and clarifies the key design decisions.

The long-awaited next version of Java EE 5 is about to be released. Java EE 5 Many new features include a patched EJB architecture, one of the salient features of which is JPA. With container and container persistence options, JPA brings a whole range of new design choices to the Java EE architect. This article focuses on the design of applications in containers that rely on EJB containers to provide enterprise services, such as transaction processing and security.

I will test with your familiar Petstore application to demonstrate the capabilities of JPA and how it challenges the traditional Java EE design patterns. This application is trivial, so it does not provide detailed implementation details. I'll use a code excerpt to illustrate the design considerations. This article assumes that you are familiar with the basic concepts of EJB 3.0 and the basic concepts of Object Relational (OR) mapping.

   Design Overview

The example Petstore application is a web-based electronic transaction application that implements the following use cases:
    • Browse Products
    • Find Products
    • Maintenance Account
    • Maintain Shopping Cart
    • Create order
This application is designed as a multi-tier Java EE application with three primary logical tiers:
    • The presentation layer (not the focus of this article) uses the Struts framework.

    • The service layer is a simple service façade that delegates all the work to its collaborators. The purpose of the service layer is to separate the service supply from the service implementation.

    • The data access Layer is a series of coarse-grained data access Objects (DAO) implementations that are implemented as stateless session beans. They all depend on the Java persistence entity manager for their persistence needs.
The application domain model is represented by an EJB 3.0 entity bean and used for communication between tiers. When a domain object leaves the data access layer, it is detached from the entity manager. When you re-enter the data access layer, it needs to reconnect to the entity manager.

Annotations seem to be a widely used feature of Java 5, and JPA is no exception. Annotations can be used to specify OR mappings--you can often see them in DW documents and tutorials--and Petstore applications use them for the same purpose. It is worth mentioning, however, that you can also specify or map by mapping files. The OR Mapping section later in this article explores and compares these two options.

I develop and deploy Petstore applications in the Jboss application server (see Resources). I use a commercial database to do most of the development work and porting the backend of the application to the PostgreSQL database (OR mapping section contains a discussion about the potential impact of the database migration you should know when using JPA).

One of the purposes of this case analysis is to meet design standards and allow highly testable implementations. As seen in the test section, you can use a series of test techniques to test your Petstore application.

The Petstore application leverages the fact that it is a regular Web application. The main advantage is that all layers are capable of running in the same JVM, eliminating the need for component distribution. The remoting section of this article provides a brief overview of how to add remoting functionality to your application.

   Service Layer

The service layer is designed as a service façade. It is implemented by Petstoreservice, a stateless session bean. The Bean has to rely entirely on its collaborators to provide WEB services.

Because simplified Petstore requirements are limited to retrieving data from a database and storing it in a database, the only collaborators are DAO. Real applications can invoke WEB services, access other applications via RMI/IIOP or resource adapters, and generate e-mail messages. All features of this type require support from other collaborators.

You can inject collaborators by @EJB or @Resource annotations (as shown in Listing 1) or by @PostConstruct methods (as shown in Listing 2):

Listing 1. Injecting collaborators with @EJB

@EJB (beanname = "Accountdao") Accountdao Accountdao;

   Listing 2. Injecting collaborators with @PostConstruct

Messagesource Messagesource; @PostConstruct public void init () {    

The main factor in selecting the test strategy for the Bean implementation class is that the class relies entirely on the collaborators to provide the service. This means that the interaction between class and collaborator needs to be validated. As you can see in the test section, the Mock object method fully satisfies that goal.

   Data Access Layer

The data access layer is designed as a series of coarse-grained DAO. DAO is implemented as a stateless session bean, and one bean corresponds to a logical domain: Accountdao, Orderdao, and Productdao.

Each bean has to inject the entity manager into it:


This is in the application Persistence invocation Class (Persistence-aware)Most of the layers. It uses a wide range of new Enterprise JavaBeans Query Language (EJB QL). All persistence-related actions occur at this level, for example:

Profile = (userprofile) em.createquery (    "from userprofile up where up.login = Login"). Setparameter (    

Here is another example:


In fact, these classes are persistent calling classes (Persistence-aware) and require a test strategy in the container, which is described in the test section.

  Domain model

You can think of JPA as a successor to well-known transparent persistence technologies such as JDO and Hibernate. Although transparent persistence can be thought of as an additional (add-on) service that can be applied to Plain old Java Objects (POJO) that ignores persistence, JPA imposes a small amount of restrictions on domain objects.

First, you typically have a (proxy) object identifier that maps to the primary key of the corresponding database table:

@Id @GeneratedValue (strategy = generationtype.sequence, generator = "Accountseq") @Column (name = "Account_sysid") public Integer Getaccountid () {    

Second, in an online transaction process (OLTP) environment, a version field or JavaBean property is required for optimistic concurrency control:

@Column (name = "Row_version") @Version public int getversion () {    

Ultimately, if you choose to use annotation-style mappings, the mapping annotations will be distributed around the code.
 
Another constraint stems from the fact that a domain object can be accessed through the same layer as the domain object managed by the entity manager, or by separating all other tiers of it. In addition, the object may be new or deleted. In general, the behavior of an object depends on its persistence state. For example, suppose you execute the following line of code in the Entity manager:


The item collection is populated with the item of a given product, and the value of the size variable is greater than 0. If you use a One-to-many association of the default lazy load (lazy) configuration and execute the same line of code in the presentation layer, the value of the size variable is 0. In other words, outside of the entity manager (it doesn't matter in the entity manager) inactive (lazy)Objects and activities (Eager)The object area is separated. The way to resolve this problem is to enforce project specifications and conventions.

In a domain object, you can apply the same inference to the business method. They should be ready to be invoked at any level, whether or not they are in the entity manager. This is the reason to limit the number of business methods in a domain object to the minimum number necessary.
  
Despite all of the above, domain objects still retain many POJO features. This means that you can test the business method with plain old Java test (POJT), pojt the term quoted Expert one-on-one Java Development without EJBA book.

   OR Mappings

An OR map is an important element of an application designed around JPA. It directly affects how the entity manager populates the domain objects. Therefore, the change mapping can be detected at the presentation layer. Changing a Get type or cascading type can have a very negative impact.

As mentioned earlier, there are two ways to define mappings: metadata (annotations) and mapping files. Although we highly advocate the use of metadata, you should also be aware of the inconvenience it brings. Essentially, this approach involves two logical tiers of the application: domain model and mapping information. Because these two layers are dispersed, the two layers need to be tested separately using different techniques. The metadata method itself does not affect the testability of the layer. More precisely, the metadata approach makes these two layers seem to be just one layer, which may cause problems due to a number of factors.

One factor that affects the selection of the mapping method is the project team structure. In small projects where only a handful of developers are involved, the number of tables is low (typically less than 100 tables) and there are no dedicated mapping staff, because annotations are usually faster, so it might be best to think of annotation methods as defining mappings. Using a mapping file is a better choice for midsize and large projects with dedicated mapping personnel or mapping teams. This approach can reduce resource contention and give the development process another degree of freedom. The metadata-based mapping method proves to be a more time-saving method for Petstore applications.

The OR mapping layer is designed to protect the rest of the application from the underlying database changes. There is no need to make any changes to the mapping layer when migrating the Petstore application backend to PostgreSQL. This may be due to the fact that both the original database and the PostgreSQL support the sequence, so the primary key generation policy remains intact. In general, you should override the mapping area associated with Object ID processing.

Comprehensive test coverage of mappings is extremely important. All relational mappings must be overwritten to ensure that the fetch behavior and transition persistence are tested. You can take advantage of the JPA used outside the container to perform this task (detailed in the next section).

  Test

The key element of the service layer design is to focus on collaboration with the underlying to provide the requested service. This requires consideration of a reliable test strategy that uses dynamic mock objects. I use the EasyMock framework to implement the test method.

The DAO layer has a strong database cohesion. This is why reliable testing requires policy and database access within a certain class of containers. Although this is easy for remote EJBS, it is important to consider a meaningful way to fit the local bean. The disturbing factors here are:

    • Requires test façade in container
    • The domain object is discontinuous, so all validation needs to occur within the container.


The JBoss embeddable EJB3 container (writing this article fashion in beta phase) has proved to be a more appropriate choice. Because the JBoss embeddable EJB3 container can be started from a unit test, all code runs in the same JVM. Testing within a container that can be embedded in a container can achieve its goal, but the process is slow because the container starts at approximately 30 seconds. This problem may be caused by an earlier product state and can be improved by a reasonable configuration.

I used POJT to test the business methods of the domain model classes. No other testing techniques are required, and other testing techniques are not suitable for these classes.

An OR mapping is a major layer that requires exhaustive test coverage. This layer is very sensitive to the database, so the layer cannot apply mock objects or POJT techniques. However, you can take advantage of JPA's container-outside capabilities. I use this strategy to test the Petstore or the or mapping layer.

You need to keep in mind the importance of test correlation and transition persistence behavior in your tests. This allows you to take early notice of changes to the type or cascading type values, and takes appropriate action.

   Remote Processing

The key feature of Petstore application design is its local characteristics. There are many advantages to having all the logical tiers of an application run in the same JVM. For a detailed discussion of the topic, seeExpert one-on-one Java Development without EJB

However, it should be stated that:Remote processing façade, you can easily add remoting capabilities to your application. The remoting façade, rather than the service façade I described earlier, exposes a remote interface that has two responsibilities: to convert between domain models and sequential data transfer objects (DTO) and to invoke the appropriate methods on the service façade.

This application can be implemented using a remote stateless session bean. The only hurdle is creating additional DTO layers and converting them to and from the domain model. However, you need it to ensure a clean interface and loose coupling with remote clients.

   Concluding remarks

EJB 3.0 and JPA will no doubt be the main selling point of Java EE 5. In some areas, they offer a competitive advantage to the normal Java community and Briber Java in other areas with competitors. (Admittedly, a standards-based approach is not yet available in certain areas.) )

For the past few years, the Spring framework has been a major competitor for EJB in the Enterprise arena. The EJB 3.0 specification addresses many of the issues that are contributing to Spring's rise. As it emerges, EJB 3.0 undoubtedly offers a better development experience than Spring-the most compelling advantage is that it does not require a configuration file.

JPA provides a standard OR mapping solution that is fully integrated into EJB 3.0-compliant containers. JPA's predecessors will continue to grow steadily, but in business applicationsRawUse will likely be reduced. Implementing JPA-compliant entity managers seems likely to be a development direction for this type of technology.

At the time of writing this article, the EJB 3.0 specification is still in the proposed final draft (proposed final Draft) phase. Here are some unresolved issues and JPA-related pre-implementation:

    • The current form of the JPA specification does not define read-only entity beans. This is confusing because entity beans that are compatible with the EJB 2.1 specification support this feature. The Spring framework also supports read-only transactions.

    • The pluggable persistence provider concept is still in an undelivered phase.

    • The standard optimistic concurrency exception-optimisticlockexception-was first seen in the EJB 3.0 proposed Final Draft. Before the persistence provider executes it, you also need to use provider-specific exceptions, such as Hibernate staleobjectstateexception, to detect optimistic concurrency issues. Temporarily, this situation restricts your implementation to only a specific persistence provider.

The larger problem with the Java EE Family specification is not related to JPA. The problem with the Java EE family specification concerns the integration between Web and EJB containers. Spring still has a major competitive advantage in this area. The JBoss Seam project tried to use a custom method to solve the problem. The Caucho Resin application Server attempts to extend the container boundary and supports the use of @EJB annotations in the Web container. We hope that Java EE 5.1 will solve the problem of layer integration and provide us with a comprehensive and standard dependency injection method.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.