Brand new experience of JavaBean (EJB) 3.0

Source: Internet
Author: User

Introduction

The long-awaited ejb3.0 specification has recently released its first draft. In this article, we will give an overview of the new specifications, including new metadata support, modifications to ejbql, and new methods and runtime environments for accessing bean context using the Entity Bean model. The author also discussed the future adjustments of EJB and the relationship between ejb3.0 and other development specifications.

Start

In any case, due to the complexity of EJB, the performance in the J2EE architecture has never been very good. EJB is probably the only one in the J2EE architecture that does not realize its ability to develop and improve productivity. The ejb3.0 specification is trying to reduce the complexity of its development in this regard. Ejb3.0 reduces the workload of developers for underlying development. It cancels or minimizes the implementation of many (which were previously required) callback methods, it also reduces the complexity of the Entity Bean and the O/R ing model.

In this article, I will first introduce several major changes in ejb3.0. It is very important to have a deep understanding of ejb3.0. Later, I will describe the details that have been submitted to the ejb3.0 specification from a higher level, and explain the changes in the new specification one by one: Entity Bean, O/R ing model, entity-link model and ejb ql (EJB Query Language.

Background

Two important changes in ejb3.0 are:ProgramAnnotation Tool and hibernate-based o/R ing model.

Metadata tools in Java 5

Java 5 (formerly j2se1.5 or tiger) adds a new program annotation tool. With this tool, you can customize annotation tags to annotate fields, methods, classes, and so on. These annotations do not affect the semantics of the program, but they can be interpreted using tools (at compilation or runtime) and additional content (such as deployment description files ), or force certain required runtime behaviors (such as the status characteristics of the EJB component ). Annotation parsing can be performed through source file parsing (such as the compiler or this ide tool) or using the APIS reflection mechanism in Java 5. Annotations can only be defined inSource codeLayer. Because all annotation tags submitted to the ejb3.0 draft have a runtime retentionpolicy, this will increase the storage space occupied by class files, however, this makes it easier for Container Manufacturers and tool manufacturers.

Hibernate

Currently, Hibernate is very popular and is a development source.CodeJava o/R ing framework is designed to free developers from tedious data persistence programming. It also has a standard hql (Hibernate query language) language, which you can see in the new ejb ql. Hibernate is very simple in terms of data query, update, connection pool, transaction processing, and entity link processing.

Overview

The submitted ejb3.0 specification involves two major changes:

1. A set of annotation-based EJB programming models, coupled with the application behavior defined in ejb2.1 through the deployment descriptor and several interfaces.

2. The new object bean persistence model and ejbql also have many important changes.

There are also some proposals, such as a new client programming model, the use of business interfaces, and the lifecycle of entity beans. Note that the ejb2.1 programming model (including the deployment descriptor and home/remote interface) is still valid. The new simplified model does not completely replace ejb2.1.

EJB comment

An important goal of the EJB specification organization is to reduce the number of original code, and they provide a perfect way to introduce it. In ejb3.0, any type of enterprise-level Bean is a simple Java object (pojo) that has been properly annotated ). Annotations can be used to define the business interface, O/R ing information, and resource reference information of beans. The effect is the same as that of the deployment descriptor and interface defined in ejb2.1. Deploy descriptors in ejb3.0 is no longer necessary; the home interface is no longer required, and you do not need to implement business interfaces (containers can do these tasks for you ).

For example, you can use the @ stateless annotation tag class to declare a Java class as a stateless Session Bean. For stateful session beans, the @ remove annotation can be used to mark a specific method. Through this annotation, the bean instance will be cleared after the method is called.

To reduce the description of the component, the organization also adopted the configuration-by-exception method, this means that you can provide a clear default value for all comments so that most common information can be inferred accordingly.

New persistence Model

The new entity bean is also a simple Java object (pojo) with annotations added ). Once accessed by entitymanager, it becomes a persistent object and a part of the persistent context. A persistent context is loosely coupled with a transaction context. Strictly speaking, it implies coexistence with a transaction session.

Entity relationships are also defined through annotations, and O/R ing is also required, and several different database standard operations are provided, in ejb2.1, this is done through the developer's own design patterns or other technologies (for example, self-increasing primary key policies ).

In-depth research

Now it is time to learn more about the ejb3.0 draft. Let's start to explore four enterprise-level beans in all ejbs and see what they look like in the new specifications.

Stateless Session Bean

In the ejb3.0 specification, writing a stateless Session Bean (slsb) only requires a simple Java file and adds @ stateless annotation to the class layer. This bean can extend the javax. EJB. sessionbean interface, but these are not necessary.

An slsb no longer needs the home interface, and no EJB needs it. Bean class can implement business interfaces or not. If no business interface is implemented, the business interface is generated by any public method. If only a few business methods are exposed to the business interface, you can use the @ businessmethod annotation for these methods. By default, all the interfaces generated are local interfaces. You can also use the @ remote annotation to declare this interface as a remote interface.

The following code defines a helloworldbean. In ejb2.1, the same bean requires at least two interfaces, one implementation class and several empty implementation methods, and the deployment descriptor.

Import javax. EJB .*;

/**
* A stateless Session Bean requesting that a remote business
* Interface be generated for it.
*/
@ Stateless
@ Remote
Public class helloworldbean {
Public String sayhello (){
Return "Hello world !!! ";
}
}

Stateful Session Bean

In addition to some special descriptions of sfsb, stateful Session Bean (sfsb) is as streamlined as slsb:

An sfsb should have a method to initialize itself (in ejb2.1, it is implemented through ejbcreate ). In the ejb3.0 specification, we recommend that you use custom methods to perform initialization and expose them to business interfaces. Before using this bean, the client calls the corresponding initialization method. Currently, it is still controversial whether the Organization provides a comment to mark a method for initialization.

The bean provider can mark any sfsb method with the @ remove annotation to indicate that the bean instance will be removed after this method is called. Similarly, the Organization is still discussing whether there is a mechanism to handle this special situation, that is, whether the bean instance is removed when this method encounters an exception.

My personal views on the above issues are as follows:

1) Should there be a comment indicating a method for initialization? In my opinion, the container can call at least one method for initialization before calling other methods. This not only avoids unnecessary errors (because the initialization method is not called), but also makes the container more explicit in determining whether sfsb instances can be reused. For the moment, I will put this issue aside. The Organization should only consider providing a comment for a method to declare that it is an initialization method.

2) My Opinion on the second question is also positive. This facilitates bean provider and client programs to control bean. There is only one legacy problem: Can I remove the bean instance if this method fails to be called? The answer is no, but it will be removed at the end of the session.

Message-driven Bean

Message-driven bean is the only bean that must implement a business interface. This interface specifies the message system that bean supports. For MDB Based on JMS, this interface is javax. JMS. messagelistener. Note that the MDB service interface is not a real service interface, but a message interface.

Entity Bean

The Entity Bean is marked with the @ entity annotation. The attribute/field in all entity beans does not need to be marked with the @ transient annotation. The persistence field of the object bean can be implemented through the JavaBean-style mechanism or declared as the public/protected field.

Entity beans can use helper classes to describe their statuses. However, instances of these classes do not have the persistent identity feature (that is, fields that uniquely identify this bean ), in fact, these helper classes are closely integrated with their Entity Bean instances, and these objects still access the Entity objects in a non-shared manner.

Object Association

Ejb3.0 also supports bidirectional one-way association between beans, which can be one-to-one, one-to-many, multiple-to-one, or multiple-to-many Association. However, the two ends of Bidirectional Association are also divided into the owning side and the inverse side. The client is responsible for notifying the database of associated changes. A clear statement must be made for many-to-many associated clients. In fact, the peer end uses isinverse = true for comments (from this end, it does not need to be explained but is inferred from another segment ). As described above, can a standard organization make EJB simple?

O/R ing

The o/R ing model in ejb3.0 has also changed from abstract-persistence-schema-based to the current hibernate-converted red mode. Although the normative organization is still discussing this, a clear model will appear in the next draft version.

For example, the O/R ing model is declared through annotations in the bean class. In addition, this method also specifies the corresponding table and field. The o/R ing model provides a set of self-developed SQL statements. In addition to some basic SQL statements, it also supports some high-level development functions. For example, if there is a field columndefinition declared through @ column annotation, you can write such an SQL statement: columndefinition = "Blob not null"

Client Program Model

An EJB client can use the @ inject annotation to obtain a bean service interface reference in an "injection" manner. You can also use another annotation @ javax. EJB. ejbcontext. lookup () to complete the above operations, but the specification does not tell us how a common Java client obtains a bean instance, because this common Java client runs in a client container, it cannot access @ javax. EJB. ejbcontex object. Now there is another mechanism to complete the above work, that is, to use a super context object: @ javax. EJB. Context (). But the specification does not indicate how to use this object in the client.

EJB QL

Ejb ql can be annotated by @ namedquery. This annotation has two member attributes: Name and querystring. Once these attributes are defined, you can point to this query through entitymanager. createnamedquery (name. You can also create a standard JDBC-style query and use entitymanager. createquery (ejbqlstring) or entitymanager. createnativequery (nativesqlstring) to execute a local query.

Ejb ql can define its parameters in two ways. The javax. EJB. query interface provides methods for defining parameters, pointing to queries, and updating data. The following is an example of an ejbql pointing to a query:

....
@ Namedquery (
Name = "findallcustomerswithname ",
Querystring = "select C from customer C where c. name like: custname"
)
....
@ Inject public entitymanager em;
Customers = em. createnamedquery ("findallcustomerswithname ")
. Setparameter ("custname", "Smith ")
. Listresults ();

The following lists some enhanced features of EJB Ql:

1) Batch update and deletion are supported.

2) Direct support for internal and external connections. Run the fetch join operation to indicate the correlated entities. Order can specify to query only a field.

3) a query statement can return more than one result value. In fact, you can return a dependent class like the following:

Select New customerdetails (C. ID, C. Status, O. Count)
From customer C join C. Orders o
Where o. Count> 100

4) supports group by and having.

5) nested subqueries of the where clause are supported.

In the submitted ejb3.0 draft, EJB Ql is very similar to standard SQL. In fact, the specification even directly supports local SQL (as we mentioned above ). This may not be very clear for some programmers. We will explain it in more detail below.

Diversity

Method permissions can be declared through @ methodpermissions or @ unchecked annotation. Similarly, the transaction attribute can also be declared through @ transactionattribute annotation. The resource reference and resource environment reference are retained in the specification. These can be declared through annotations, but there are some minor differences. For example, the context environment must be controlled by the injection tool. The container automatically initializes an appropriate declared instance variable based on bean reference to the external environment. For example, you can obtain a data source as follows ):

@ Resource (name = "mydatasource") // type is inferred from variable
Public datasource customerdb;

In the preceding example, if you do not specify the name of the referenced resource, customerdb is considered as the default value. When all the reference attributes are available, the @ injec annotation can be written as follows:

@ Inject public datasource customerdb;

The container initializes the customerdb data source instance at runtime. Before that, the deployer must define these resource attributes in the container.

A better message is that the exceptions that must be detected before will never be returned. You can declare any application exception without throwing or capturing other exceptions such as createexception and finderexception. The container throws a system-level exception encapsulated in javax. EJB. ejbexception or only throws the illegalargumentexception or illegalstateexception exception when necessary.

EJB file processing mode

Before we end this section, let me take a quick look at possible changes to the EJB processing mode of Container service providers. There is no clear statement in the Specification, but I can think of at least two modes.

One way is to use the EJB file to generate a file similar to the ejb2.1 deployment mode (including necessary interfaces and deployment descriptors) and then deploy the EJB component in a way similar to ejb2.1. Of course, the resulting deployment descriptor may not be standard, but it can solve the problem that the same container is compatible with ejb2.1 and ejb3.0. The following figure describes the process.

Another method is similar to the JSP hosting deployment mode. You can put an EJB file in a pre-defined directory, and then the container will identify the EJB and process it, and then deploy and make it usable. This method can be built on the above method, which is of great help in supporting repeated deployment. Considering that the simplicity of deployment is also one of the purposes of ejb3.0 specifications, I sincerely hope that a model (at least one informal one) can be determined when the next draft comes out ).

What do you think?

The establishment of the ejb3.0 specification is in an orderly manner. In order to make EJB development easier, the efforts made by the EJB specification organization are obvious to all. As they said, everything becomes simple, but it is not easy to do so. At present, 50 annotation tags have been defined (several more will be released in the next draft), each with its own default rules and other operations. Of course, I really don't want ejb3.0 to be converted into a rebuild of ejb2.1 "EJB 3.0 = EJB 2.1 for Dummies" (I hope this equation will not be true ). Finally, I can't help but raise my own points:

1) First, the specification makes repeated deployment easy, and there is a simple mode to access the runtime environment. I still think the home interface should be abandoned.

2) In earlier EJB specifications, entity beans are used to map a persistent storage. Theoretically (maybe theoretically), you may need to map the Entity Bean to a legacy EIS (Enterprise Information System) system. For future expansion considerations, this is advantageous, and more business data models can adopt entity beans. As a result, the complexity of the bean makes the Entity Bean not optimistic. In the draft submitted this time, an entity bean is only a database ing. In addition, it is a simpler development based on non-Abstract persistence mode and simple data access mode.

3) I have a reserved attitude towards model changes. I think it is not a good idea to include SQL script fragments in ejbs. Some developers are totally opposed to containing some "SQL fragments (sqlness)" (such as @ table and @ column annotations ). My point is that these sqlness are good, so we can clearly understand what we want to do for the database. However, some SQL segments do not seem very good to me, such as columndefinition = "Blob not null", which makes the coupling between EJB code and SQL too tight.

4) Although local SQL support seems attractive, embedding SQL in EJB code is a bad idea. Of course, some methods can avoid hard-coding SQL in EJB, but this should be explained in the Specification, rather than the mode defined by some developers.

5) Assume that @ table annotation is only used for classes. At runtime, the table name defined by the name attribute of @ table annotation must correspond to an actual database table. The specification should give a clear description and a consistent model.

6) The specification also needs to clearly describe the client programming model, especially the common Java client. All references in the Specification assume or implicitly use the EJB client. In addition, there is no clear statement about the backward compatibility of the client in the specification.

7) the transient comment should be renamed to avoid conflicts with the existing transient keywords. In fact, we prefer to slightly deviate from the configuration-by-exception principle and define a @ persistent annotation to clearly define the persistence field. @ Persistent annotation can be just a tag annotation or it can have several attributes to associate the O/R ing annotation.

Association with other specifications

Currently, JSR that may affect ejb3.0 includes jsr175 (Java metadata tool) and jsr181 (Java Web Service metadata)

Jsr175 has been initially completed and won't have too many conflicts with ejb3.0; however, jsr181 and ejb3.0 have two associations:

1) web service interface: The EJB specification will adopt a mechanism to adapt to jsr181 so that a bean can be implemented as a web service and tell the Web service how to be called by the client.

2) JSR 181 plans to adopt different mechanisms to handle security issues. In earlier specifications, EJB suggested a consistent mechanism (methodpermissions), but JSR 181 planned to use a slightly different method (securityroles and securityidentity annotations ). The definition of the same RunAs annotation also has these differences. This problem is still solved and will eventually maintain its consistency in the J2EE layer specification.

Some development specifications in J2EE 1.5 may be associated with ejb3.0. There are no other development specifications that conflict with ejb3.0 except the associations mentioned above.

Conclusion

We still have a long way to go before making EJB development simple and efficient. Standardized organizations have made a good start in reducing the difficulty of EJB development. The proposal of the O/R ing model is still in the early stage, and the normative organization is improving it. I hope it is neither too complex nor overly coupled with SQL. Let us not just stay in expectation, Hope, thinking and request: put your thoughts and send your suggestions to the organization's ejb3-feedback@sun.com. JCP is not a very democratic organization, but your suggestions must be valuable.

The point in this article is that the author's personal opinion has nothing to do with the company where the author is located. I am very grateful to Hemant khandelwal for his help in this article.

The download code is the sample code of the ejb3.0 draft. This example is not verified because there is no tool or environment support. The code is just an example of the future ejb3.0.

Anil Sharma is a Senior Programmer who develops WebLogic Integration products in BEA System. He worked in Oracle and pramati before joining Bea and has been working on J2EE technology. In his spare time, he enjoys listening to music and watching movies. He also participates in the development of some open-source projects.

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.