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 the use of the program Annotation Tool in Java 5 and the O/R ing model based on Hibernate.
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 at the source code layer. 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. It is a Java O/R ing framework for source code development. It aims 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.