A survey of EJB3.0 new norms and its future development

Source: Internet
Author: User
Tags abstract define implement sql table name variable java web access
Specification Introduction

The long-awaited EJB3.0 specification has recently released its first draft. A brief overview of the new specification is presented in this article, including new metadata support, EJBQL modifications, the entity Bean Model's access to the bean context and the run-time environment, and so on. The author also discusses the future adjustment of EJB and the relationship between EJB3.0 and other development specifications.

   Start

In any case, because of the complexity of EJB, the performance in the Java EE architecture has not been very good. EJB is probably the only organization in the Java EE architecture that has not honoured its ability to simply develop and increase productivity. The EJB3.0 specification is trying to make efforts in this area to mitigate the complexity of its development. EJB3.0 eases the developer's effort to lower the underlying development, eliminating or minimizing the implementation of a number of callback methods that previously had to be implemented, and reducing the complexity of the entity bean and the O/R mapping model.

In this article, I will first introduce some of the major changes in EJB3.0. It is very important for further insight into 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: Entity BEAN,O/R mapping Model, Entity Relational model and EJB QL (EJB Query Language), and so on.

   background

Two important changes in EJB3.0 are: Using the program annotation tool in Java5 and the O/R mapping model based on hibernate.

The metadata tool in the JAVA5.

A new program annotation tool has been added to Java5 (formerly known as j2se1.5 or Tiger). With this tool you can customize the annotation tags to annotate fields, methods, classes, and so on by using these custom tags. These annotations do not affect the semantics of the program, but they can be interpreted using tools (compile-time or runtime) to produce additional content (such as a deployment profile), or to force certain run-time behaviors (such as the state attributes of an EJB component). Annotations can be parsed through source file parsing (such as compilers or the IDE tool) or by using the APIs reflection mechanism in JAVA5. Annotations can only be defined at the source code level. Because all annotation tokens submitted to the EJB3.0 draft have a run-time retentionpolicy, they increase the amount of storage space occupied by the class file, which is convenient for container manufacturers and tool manufacturers.

Hibernate

Currently hibernate is very popular, it is the development of the source code Java O/R mapping framework, the purpose is to get developers from tedious data persistence programming free. It also has a standard HQL (Hibernate query Language) language, and you can see its shadow in the new EJB QL. Hibernate is very simple in processing such as data query, update, connection pooling, transaction processing, Entity relationship processing and so on.

   Overview

There are two major changes in the EJB3.0 specification that have been submitted:

1. A set of annotated EJB programming models coupled with application behavior defined by the deployment descriptor and several interfaces defined in EJB2.1.

2. The new entity bean Persistence model, EJBQL also has a number of important changes.

There are also some suggestions for the above, such as a new client-side programming model, the use of business interfaces, and the lifecycle of entity beans. Note that the EJB2.1 programming model, including deployment descriptors and Home/remote interfaces, is still valid. The new simplified model does not completely replace the EJB2.1 model.

   EJB Annotations

An important goal of the EJB specification organization is to reduce the number of original code, and they provide a perfect and concise approach to this. In EJB3.0, any type of enterprise bean is simply a simple Java object (POJO) with the appropriate annotations. Annotations can be used to define a bean's business interface, O/R mapping information, resource reference information, and the effect is the same as defining a deployment descriptor and interface in EJB2.1. Deploying descriptors in EJB3.0 is no longer necessary; The home interface is gone and you don't have to implement a business interface (the container can do that for you).

For example, you can use the @stateless annotation tag class to declare a Java class as a stateless reply bean. For stateful-reply beans, @Remove Annotations can be used to mark a particular method, which indicates that an instance of the bean is purged after the method is invoked.

To reduce the descriptive information for the description component, the specification organization also incorporates the means by which the exception is configured (configuration-by-exception), meaning that you can provide a clear default value for all annotations, so that most conventional information can be inferred.

   the new persistence model

The new entity Bean is also an annotated simple Java object (POJO). Once it is accessed by Entitymanager it becomes a persistent object and becomes part of the persistence context. A persistence context is loosely coupled with a transaction context; Strictly speaking, it implicitly coexists with a transaction session.

Entity relationships are also defined by annotations, and the O/R mapping also provides several different database specification operations, which are accomplished through the developer's own design pattern or other technology (for example, the EJB2.1 primary key policy).

   In-depth study

Now is the time to learn more about the EJB3.0 draft. Let's start with four enterprise-class beans in all ejbs and see what they look like in the new specification.

Stateless reply bean

In the EJB3.0 specification, writing a stateless reply bean (SLSB) requires just a simple Java file and adding @stateless annotations to the class layer. This bean can extend the Javax.ejb.SessionBean interface, but these are not required.

A slsb no longer needs a home interface, and no EJB needs it anymore. A bean class can implement a business interface or do not implement it. 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, these methods can use @businessmethod annotations. By default, all generated interfaces are local (native) interfaces, and you can use @remote annotations to declare this interface to be remote (remote).

The following lines of code can be defined as a helloworldbean. In EJB2.1, the same bean requires at least two interfaces, one implementation class and several empty implementations, plus a deployment descriptor.

Import javax.ejb.*;

/**
* A stateless session beans requesting that a remote business
* Interface be generated for it.
*/
@Stateless
@Remote
public class Helloworldbean {
Public String SayHello () {
Return to "Hello world!!!";
}
}


Stateful Back Bean

In addition to the special descriptions of several SFSB, there are state-reply beans (SFSB) as streamlined as SLSB:

• A SFSB should have a way to initialize itself (in EJB2.1 by Ejbcreate ()). It is recommended in the EJB3.0 specification that these initialization actions be done through a custom method and expose them to the business interface. The appropriate initialization method is invoked by the client before using this bean. There is still a controversy over whether the specification organization is providing a comment to mark a method for initialization.

· The bean's provider can mark any SFSB method with a @remove annotation to show that the instance of the bean will be removed after the method is invoked. Similarly, the normative organization is still discussing whether there is a mechanism to handle this particular situation, that is, if the instance of the bean is removed if the method is abnormal.

Here are my personal views on the above questions:

• Should there be a comment to indicate a method for initialization? My point is--there should be, so that the container can invoke at least one method to initialize before invoking other methods. This not only avoids unnecessary errors (since the initialization method is not invoked) but also allows the container to make a clearer decision as to whether the SFSB instance can be reused. Let me put this question aside for a moment, the normative organization only considers providing a comment for a method to declare that it is an initialization method.

• My point of view for the second question is also yes. This facilitates the bean's provider to control it with the client program. There is only one remaining question: Is it possible to remove an instance of this bean once this method fails to be invoked? The answer is no, but it will be removed at the end of the conversation.

Message-driven beans

The message-driven bean is the only bean that must implement a business interface. This interface indicates which message system the bean is supporting. For a JMS based MDB, this interface is Javax.jms.MessageListener. Note The MDB business interface is not a real business interface, it's just a message interface.

Entity Beans

• Entity beans are marked with @entity annotations, and properties/fields in all entity beans do not have to be marked with @transient annotations. The persisted field of an entity bean can be implemented either by Javabean-style mechanism or by declaring it as a public/protected field.

• Entity beans can use helper classes to describe their state, but instances of these classes do not have the attributes of persistent uniqueness (that is, fields that uniquely identify the bean, and so on), and actually these helper classes are tightly bound to their entity bean instances persistent , and these objects are also accessed in a unshared manner.

Entity Associations

EJB3.0 also supports bidirectional, one-way associations between beans, which can be a pair of one or one pairs, many-to-many, or many-to-many associations. However, the two ends of the two-way association are also divided into their own end (owning side) and the other side (inverse side) different ends. The self side is responsible for informing the database of the associated changes. For a many-to-many association The self end must be explicitly stated. In fact, the other end is annotated via Isinverse=true (this is not necessarily explained by the other side). It seems that the description of the above, the normative organization can also say that the EJB is easy to change it?

O/R mapping

The O/R mapping model in EJB3.0 has also changed significantly from the original abstract-persistence-schema-based to the current hibernate-inspired pattern. Although the current regulatory organization is still discussing this, a clear model will appear in the next version of the draft.

For example, the O/R mapping model will be declared through annotations in the Bean class. And this method also indicates the specific table and field. The O/R mapping model provides a set of own SQL, and supports some high-level development functionality in addition to providing some basic SQL. For example, there is a field columndefinition declared through a @column annotation, so you can write such sql:columndefinition= "BLOB not NULL"

Client program Model

An EJB client can obtain a business interface reference for a bean in a "injected" way @Inject annotations. You can also use another annotation @javax. Ejb.EJBContext.lookup () to do the above, but the specification does not tell us how a typical Java client obtains an instance of a bean, Because this normal Java client is running in a client container, it cannot access the @javax.ejb.ejbcontex object. Now there is another mechanism to do the work that is using a Hyper context object: @javax. Ejb.context (). However, the specification does not indicate how this object is used in the client.

EJB QL

EJB QL can be annotated by @namedquery. This annotation has two member properties, respectively, name and querystring. Once these attributes are defined, you can point to the query by Entitymanager.createnamedquery (name). You can also create a standard JDBC-style query and use Entitymanager.createquery (ejbqlstring) or entitymanager.createnativequery (nativesqlstring) (This method is used to execute a local query) to execute the query.

The EJB QL has two places to define its parameters. The Javax.ejb.Query interface provides methods for defining parameters, pointing to queries, updating data, and so on. Here is an example of a ejbql point 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 ();
Some of the enhancements to the EJB QL are listed below:

• Support for bulk updates and deletions.

• Direct support for both internal and external connections. The FETCH join runs you point to the associated entity, and the order can specify that only one field is queried.

• The query statement can return more than one result value. In fact, you can return a dependency analogy as follows:

SELECT New CustomerDetails (C.id, C.status, O.count)
From Customer c JOIN c.orders o
WHERE o.count > 100
• Supports group by and having.

• Nested subqueries that support WHERE clauses.

In the draft EJB3.0 submitted, EJB QL is very close to standard SQL. In fact, the specification even directly supports local SQL (as we mentioned above). This may not be clear to some programmers, and we'll explain it in more detail below.

Diversity

Method permissions can be declared by means of @methodpermissions or @unchecked annotations; Similarly, transaction properties can be declared by @TransactionAttribute annotations. Resource references and resource environment references are still retained in the specification. The same can be stated through annotations, but there are some subtle differences. For example, the context environment is controlled by an injection tool. The container automatically initializes an appropriate declared instance variable based on the bean's reference to the external environment. For example, you can get a data source (DataSource) as follows:

@Resource (name= "myDataSource")//type is inferred from variable
Public DataSource Customerdb;
In the above example, if you do not specify a reference resource name (name), then the CUSTOMERDB will be considered the default value. When all of the referencing properties are available, @Injec comments can be written like this:

@Inject public DataSource Customerdb;
The container is responsible for initializing the CUSTOMERDB data source instance at run time. The Deployer must define these resource properties in the container before this.

The better news is that the exceptions that must have been detected before will be gone forever. You can declare arbitrary application exceptions without having to throw or catch other exceptions like CreateException and Finderexception. The container throws a system-level exception encapsulated in the Javax.ejb.EJBException or throws IllegalArgumentException or illegalstateexception exceptions only when necessary.

   EJB file processing mode

Before we close this section, let me quickly scan the container provider for possible changes in EJB processing mode. There is no clear stance on this in the specification, but I can think of at least two models.

• One approach is to use the EJB file first to generate files similar to the EJB2.1 deployment pattern (including the necessary interfaces and deployment descriptors) and then deploy the EJB component in a similar EJB2.1 manner. Of course, the resulting deployment descriptor may not be standard, but it solves the problem of EJB2.1 and EJB3.0 compatibility with the same container.

• Another approach is a deployment pattern similar to JSP todo. You can put an EJB file in a predefined directory, and then the container will recognize the EJB and process it, then deploy and make it available. This method can be built on top of the above method and is helpful in support of repeated deployments. Considering the simplicity of deployment is also one of the purposes of the EJB3.0 specification, I sincerely hope that the next draft will be able to identify a model (at least one informal).

   What do you have in mind?

The EJB3.0 specification is being developed in an orderly fashion, and the efforts made by EJB specification organizations are obvious to make EJB development easier. As they say, everything is going to be easy, but it's not easy to do that. 50 annotation tags are currently defined (and several will be published in the next draft), each with its own default rules and other actions. Of course, I really don't want EJB3.0 to turn into a EJB2.1 "EJB 3.0 = EJB 2.1 for Dummies" (hopefully this equation will not be established). Finally, I can't help but mention some of my own ideas:

• First, the specification does make it easy to deploy over and over again, and there is a simple pattern to access the runtime environment. I still think the home interface should give up.

• In the early EJB specification, entity beans are used to map a persistent store. In theory (and perhaps only theoretically), entity beans may need to be mapped to a legacy EIS (Enterprise Information System). This is beneficial for future expansion considerations and allows for more business data models to take on entity beans. And so its accompanying complexity makes entity beans less bullish. In this draft submission, an entity bean is just a mapping of a database. And it is simpler to develop based on non-abstract persistence patterns and simple data access patterns.

• I have reservations about model changes, and I don't think it's a good view to include SQL script fragments in EJBS. Some developers are completely opposed to including some "SQL Fragment (Sqlness)" (such as @Table and @Column annotations). My point is that these sqlness are good, so we can know exactly what we want the database to do. But some of the SQL segments do not look good to me, such as columndefinition= "BLOB not NULL," which makes the coupling between EJB code and SQL too tight.

• Although support for local SQL seems tempting, embedding SQL in EJB code is a very bad idea. Of course, there are ways to avoid hard-coded SQL in EJBs, but this should be explained in the specification and not by some of the developers ' own defined patterns.

• Suppose @table annotations are used only for classes. The table name defined at run time through the Name property of the @table annotation will have to correspond to an actual database table. The specification should give a clear explanation and a consistent pattern for this.

• The specification also requires a clearer description of the client programming model, especially for ordinary Java clients. All references in the specification assume or implicitly use the EJB client. And there is no explicit explanation for the backward compatibility of the client in the specification.

· Transient annotations should be renamed to avoid conflicts with existing transient keywords. In fact, at this point we are more willing to deviate a little from the configuration-by-exception principle and define a @persistent annotation to define the persisted field explicitly. A @Persistent annotation can be just a markup annotation or it can have several properties to associate with the O/R mapping annotation.

   association with other specifications

There are JSR175 (Java language metadata tools) and JSR181 (Java Web Service metadata) that may currently affect EJB3.0

JSR175 has been preliminarily completed and will not have much conflict with EJB3.0, but JSR181 has two associations with EJB3.0:

· 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 invoked by the client.

· The JSR 181 program uses different mechanisms to address security issues. EJB suggested using a consistent mechanism (methodpermissions) in earlier specifications, but JSR 181 plans to use a slightly different approach (Securityroles and securityidentity annotations). The same definition of the RunAs annotation also has these variations. This problem will eventually be resolved in the Java-EE layer of the specification to maintain its consistency.

Some of the development specifications in Java EE 1.5 may be associated with EJB3.0. There are no other development specifications that conflict with the EJB3.0, except for the few associations mentioned above.

   Concluding remarks

We still have a long way to go before we can make EJB development simple and efficient. Standardizing the organization has been a good start in reducing the difficulty of EJB development. The proposal of the O/R mapping model is still in its early stages, and the normative organization is perfecting it. I hope it's not too complicated and not overly coupled with SQL. Let's not just stay in expectations, hopes, thoughts, and requests: put forward your thoughts and send your suggestions to the normative organization ejb3-feedback@sun.com. JCP is not a very democratic organization, but your advice must be valuable.



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.