This article introduces a design method of Java platform and Enterprise Edition (Java ee 5), which utilizes the new Java persistence API (JPA) of Enterprise JavaBeans (EJB) 3.0 ). JPA provides a standard Object link ing solution that avoids dependency on third-party frameworks (such as Hibernate ). You will see the details of the sample application, which validates this method and clarifies the key design decisions.
The long-awaited next version of Java ee 5 will be released soon (see references for links to the standard and preview versions ). Many new features of Java ee 5 include the patched EJB architecture. One of its outstanding features is JPA. With the persistent options inside and outside containers, JPA brings a series of brand new design choices to J2EE architects. This article focuses on the design of applications in containers. Such applications rely on EJB containers to provide enterprise services, such as transaction processing and security.
I will use your familiar PetStore application for testing to prove the functionality of JPA and how it challenges traditional J2EE design patterns. This application is trivial, so detailed implementation details are not provided. I will use code excerpt to describe the design considerations (for the complete open source code connection, see download ). This document assumes that you are familiar with the basic concepts of EJB 3.0 and object relationship (OR) ing. (For more information about these topics, see references ).
Design Overview
The example PetStore application is a web-based electronic transaction application that implements the following use cases:
- Browse Products
- Search for products
- Maintain account
- Maintain shopping cart
- Create order
This application is designed as a multi-layer Java EE application with three main logic layers:
- Presentation Layer(Not the focus of this article) use the Struts framework.
- Service LayerIs a simple service facade that delegates all work to its collaborators. The purpose of the service layer is to separate service supply and service implementation.
- Data access layerIs a series of coarse granularity implemented as stateless session beansData access objects(Dao) (see references ). For persistence, they all depend on the Java persistence Entity Manager.
The application domain model is represented by the EJB 3.0 Entity Bean and used for inter-layer communication. When the domain object leaves the data access layer, it is detached from the object manager. When you re-enter the data access layer, it needs to re-connect to the object manager.
Annotations seem to be a widely used feature of Java 5, and JPA is no exception. Annotations can be used to specify or ing-you can often see in DW documents and tutorials-And PetStore applications use them for the same purpose. However, it is worth mentioning that you can also specify or ing through the ing file. Later in this article, the OR ing section will discuss and compare the two optional methods.
I develop and deploy the PetStore application on the JBoss Application Server (see references ). I use a commercial database to complete most development work and port the application back-end to the PostgreSQL database (the or ing section contains a discussion about the potential impact of database migration when using JPA).
One of the purposes of this case analysis is to comply with design standards and allow highly testable implementations. As you can see in the test section, you can use a series of test techniques to test the PetStore application.
The PetStore application makes full use of the fact that it is a Web application of rules. The main advantage is that all layers can run in the same JVM, eliminating the need for component distribution. This topic describes how to add the remote processing function to an application.
Service Layer
The service layer is designed as a service facade. It consistsPetStoreService
This stateless Session Bean implementation. Bean relies entirely on its collaborators to provide web services.
Because the simplified PetStore requirement is limited to retrieving data from the database and storing the data in the database, the only co-author is Dao. Real applications can call web services, access other applications through RMI/IIOP or resource adapter, and generate email messages. All functions of this type must be supported by other collaborators.
Available@EJB
Or@Resource
Inject comments to collaborators (as shown in Listing 1) or@PostConstruct
Method injection collaborators (as shown in List 2 ):
List 1. Inject collaborators using @ EJB
@EJB(beanName = "AccountDao")AccountDao accountDao; |
List 2. Use @ postconstruct to inject collaborators
MessageSource messageSource;@PostConstructpublic void init() { messageSource = new MessageSourceImpl("exceptions");} |
The main factor for selecting bean implementation class testing policies is that the class fully relies on collaborators to provide services. This means that the interaction between classes and collaborators needs to be verified. As you can see in the test section, the method of imitating an object fully meets this 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 a bean corresponds to a logical domain:AccountDao
,OrderDao
AndProductDao
.
Every bean needs to inject the Entity Manager into it:
@PersistenceContext(unitName = "manager1")protected EntityManager em; |
This is in the ApplicationPersistence-aware)The largest layer. It is widely used with the brand new Enterprise JavaBeans Query Language (ejb ql) (see references ). All persistence-related actions occur at this layer. For example:
profile = (UserProfile) em.createQuery( "from UserProfile up where up.login = :login").setParameter( "login", login).getSingleResult(); |
The following is another example:
In fact, these classes are persistent call classes (persistence-aware) that require an in-container test policy, which will be described in the test section.
Domain Model
You can regard JPA as the successor of the well-known transparent persistence technology (such as JDO and hibernate. Although transparent persistence can be seen as an add-on service, it can be applied to plain old Java objects (pojo) that ignore persistence, however, JPA still imposes a small number of restrictions on domain objects.
First, you usually have a (proxy) object identifier mapped to the primary key of the corresponding database table:
@Id@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "AccountSeq")@Column(name = "account_sysid")public Integer getAccountId() { return this.accountId;} |
Second, in the online transaction process (OLTP) environment, a version field or JavaBean attribute is required for Optimistic Concurrency Control:
@Column(name = "row_version")@Versionpublic int getVersion() { return version;} |
Finally, if you select to use the annotation ing method, the ing annotation will be distributed around the code.
Another restriction stems from the fact that a domain object can be accessed through the layer of the domain object managed by the Entity Manager, or by separating all other layers of the domain object. In addition, the object may be new or deleted. In general, the behavior of an object depends on its persistence state. For example, run the following line of code in the Entity Manager:
int size = attachedProduct.getItems().size(); |
The item set is filled with items of the given product,size
The variable value is greater than 0. If one-to-multiple associations configured by lazy are used by default, and the same line of code is executed in the presentation layer,size
The variable value is 0. In other words, the object manager cannotLazy)Object andActivity (EAGER)Objects are separated. The solution to this problem is to enforce the project specifications and conventions.
In a domain object, you can apply the same reasoning to the business method. Whether or not they are in the Entity Manager, they should be ready to be called at any layer. This is the reason to limit the number of business methods in the domain object to the minimum necessary quantity.
Despite the above situations, domain objects still retain many pojo features. This means that you can use plain old Java test (pojt) to test the business method.Expert one-on-one J2EE development without EJB(See references .)
Or ing
Or ing is an important element of applications designed around JPA. It directly affects how the object manager fills in domain objects. Therefore, the change ing can be noticed in the presentation layer. Changing the acquisition type or cascade type may have a very negative impact.
As described above, there are two methods to define mappings: Metadata (annotations) and ing files. Although we strongly advocate the use of metadata, you should also note the inconvenience it brings. Essentially, this method involves two logic layers of the application: domain model and ing information. Because these two layers are scattered, they need to be tested separately using different technologies. The metadata method does not affect the testability of the layer. More specifically, the metadata method makes the two layers seem to be only one layer. This may cause problems due to a series of factors.
One factor that affects the selection of ing methods is the project group structure. In small projects with only a few developers involved, the number of tables is very small (generally less than 100 tables) and there is no full-time ing staff, because annotations are usually faster, so it may be the best choice to regard the annotation method as the definition ing. For medium-sized and large projects with full-time ing staff or ing groups, the use of ing files is a better choice. This method can reduce resource contention and give the development process another degree of freedom. The metadata-based ing method proves to be a more time-saving method for PetStore applications.
The or ing layer is designed to protect other applications from changes to the underlying database. When the PetStore application is migrated to PostgreSQL at the backend, no changes need to be made to the ing layer. This may be due to the fact that both the original database and PostgreSQL support sequences, so the primary key generation policy remains intact. Generally, you should overwrite the ing areas related to object ID processing.
It is extremely important to fully test the coverage of ing. All link mappings must be overwritten to ensure that the acquisition behavior and transition persistence are tested. You can use JPA outside the container to execute this task (this will be detailed in the next section ).
Test
The key element of service layer design is to focus on collaboration with the underlying layer to provide requested services. This requires the use of a reliable testing strategy that dynamically imitates objects. I used the easymock framework (see references) to implement the test method.
The Dao layer has powerful database cohesion. This is why reliable testing requires access to certain types of container policies and databases. Although this is very easy for remote ejbs, you still need to consider meaningful methods suitable for local beans. The disturbing factors here are:
- Facade needs to be tested in the container
- Domain objects are non-consecutive, so all verification needs to happen in the container.
The JBoss embeddable ejb3 container (see references) has been proven to be a more appropriate choice. Because the JBoss embeddable ejb3 container can be started from the unit test, so that all code runs in the same JVM. It can be achieved by testing in a container that can be embedded in the container, but the process is slow, because the container startup time takes about 30 seconds. This problem may be caused by the early product status and can be improved through reasonable configuration.
I use pojt to test the business methods of the domain model class. Other testing technologies are not applicable to these classes.
Or ing is a main layer that requires overwrite tests. This layer is very sensitive to databases, so this layer cannot be used to imitate objects or pojt technology. However, you can use the out-of-container functions of JPA. I use this policy to test the PetStore or ing layer.
Keep in mind the importance of testing associations and transitional durable behavior in the test. In this way, you can get the type change or cascade type value change as soon as possible, and take appropriate measures.
Remote Processing
The key feature of PetStore application design is its local features. This method has many advantages when all the logic layers of the application are running in the same JVM. For more information about this topic, seeExpert one-on-one J2EE development without EJB(See references ).
However, it should be noted that: PassRemote facade ProcessingYou can easily add the remote processing function to the application. The remote processing facade (instead of the Service facade I described earlier) Exposes a remote interface, which has two responsibilities: domain model and ordered data transmission object (DTO) (see references) and call appropriate methods on the service facade.
You can use a remote stateless Session Bean to implement this application. The only obstacle is to create other DTO layers and switch between them and the domain model. However, you need it to ensure a clean interface and loose coupling with remote clients.
Conclusion
Ejbs 3.0 and JPA are undoubtedly the main selling points of Java ee 5. In some fields, they bring a competitive advantage to the normal Java Community and make Java different from competitors in other fields. (It is undeniable that there are no standard-based methods in some fields currently .)
Over the past few years, Spring framework (see references) has been the main competitor of EJB in the enterprise field. The EJB 3.0 specification solves many issues that promote the rise of spring. With its appearance, EJB 3.0 undoubtedly provides a better development experience than spring-the most striking advantage is that it does not need configuration files.
JPA provides a standard or ing solution that is fully integrated into EJB 3.0 compatible containers. JPA's predecessors will continue to develop steadily, butRawUsage may be reduced. The Entity Manager that implements JPA compatibility seems likely to be the development direction of such technology.
At the time of writing this article, the EJB 3.0 specification is still in the proposed final draft stage (see references ). The following are some unsolved issues and pre-implementations related to JPA:
- • The current JPA specification does not define read-only entity beans. This is confusing because entity beans 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 the undelivered stage.
- • Standard Optimistic Concurrency exception-optimisticlockexception-first appeared in EJB 3.0 proposed final draft. Before the persistence provider executes it, you also need to use provider-specific exceptions, such as staleobjectstateexception of hibernate, to detect Optimistic Concurrency issues. For the time being, this situation limits that your implementation can only use a specific persistent provider.
The major issues of the Java EE series specifications have nothing to do with JPA. Java EE specifications involve integration between web and EJB containers. Spring still has major competitive advantages in this field. The JBoss Seam project (see references) tries to use a custom method to solve this problem. Caucho Resin Application Server (see references) tries to expand container boundaries and supports the use@EJB
Annotations. 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.