EJB3.0 Sneak peek (programmer 0408 article)

xiaoxiao2021-03-06  73

EJB 3.0 sneak peek

Writing / transparent

In the past two months, we constantly hear all the rumors of EJB 3.0 from various channels. At the Theserverside Annual Meeting and the Javaone Conference, the discussion surrounded by EJB 3.0 is always the most enthusiastic person. And J2EE developers who only see only scales are here, seeing the attitude of EJB 3.0 is also different - the advancement of lightweight programs regard it as the subversion of J2EE's old forces, lightweight technology Victory; EJB's horses are lightly written, and there are only some surface articles that do not change the medicine here. Just last week (accurately said,

6

month

twenty four

day

), Sun released the first preview version of the EJB 3.0 specification, and we finally have the opportunity to see the true face behind the mysterious veil. Although the ultimate specification may be determined for a year, although the standardized content may change, as a responsible J2EE developer, a curious programmer, we still need to understand this future mainstream technology as soon as possible. Now, let the author accompany you into the new world of EJB 3.0.

Reader's request

In principle, this is just an introductory article, does not involve excessive details. However, in order to better understand the concept of EJB 3.0, readers are best to have basics of EJB 2.1. Also, if you can prepare some knowledge about Java 1.5 (eg JSR 175 Metadata Annotation and JSR 14 Generic), it will be helpful to read this article - the reader can "understand" "Programmer" in 2003 This information is obtained in the "Six Term".

Summation

Compared with EJB 2.1, the biggest improvement in EJB 3.0 is to simplify EJB development work. For compatibility, the application server that implements EJB 3.0 specification will fully support EJB 2.1, and new specifications have not replaced or discard any old API. That is, if you like, you can completely ignore the new features brought by EJB 3.0, still go to the 2.1 way to develop EJB. I believe this is a good news for many application developers. After all, the more of the technology will always bring some pain.

The maximum goal of EJB 3.0 is to minimize the complexity of the EJB architecture from the perspective of application developers. Until now, developing EJB still means inheriting some interfaces that are unrelated to business (such as Javax.ejb.ejbObject), operate some object-independent objects (such as JNDI queries, ejbhome), write complex profiles. A good IDE (such as WebLogic Workshop) simplifies these work, but using IDE often means that the vendor binding and application server binding. EJB 3.0 hopes to fundamentally simplify these complex work, and most of the work here is quite mechanically.

In order to achieve this goal, EJB 3.0 takes the following measures:

• Record the EJB metadata (such as EJB type, configuration information, etc.) with Java metadata annotation. The use of metadata labels can reduce the number of artifacts required by developers, such as the configuration descriptor (deployment descriptor) will be automatically generated by the application server, and the EJB interface can also be from one Pojo (Plain-Old Java Object, ordinary Java objects) class automatically generates.

• Use the "only special case" policy: In most cases the default configuration, only the developer is written by the developer in special cases, thereby avoiding the development of the developer to write a large number of common, expected behavior. .

By means of metadata annotation, relying on the injection mechanism [1] and simple lookup mechanisms, the dependence and JNDI access to the application server environment will be reduced, and the development and use is reduced, and the portability of the EJB component is enhanced. Use. • Simplify the type of EJB. The new EJB component is more similar to Pojo (or ordinary java bean), and the interface type required for runtime will be automatically generated by the application server according to the metadata label. EJB's business interface does not need to inherit the specific interface of the session bean or Entity Bean, but a normal Java interface (in fact, the Entity Bean does not need to implement any interfaces). And ejbcreate (), the callback method such as ejbremove () is no longer necessary, thereby greatly enhances the testability of the EJB component: you can test them outside the EJB container.

• The client does not need to use the Home interface.

• Simplify the use of container management persistence (CMP), providing a set of metadata labels for specifying an O / R mapping property; at the same time, more powerful O / R mapping capabilities are provided: support light Summary field modeling, supporting the inheritance and polymorphism of Entity Beans, greatly enhances the function of EJB QL.

• Reduce the use of Checked Exception.

Below, let's experience the development experience of EJB 3.0, I think you will like this experience.

EJB class and business interface

When programming with EJB 3.0 API, the EJB class is the main (usually also unique) workpiece that developers need to submit. This class is a typical Pojo Bean. Developers need to write all of its code and can be labeled with the Java metadata supplied with EJB 3.0 specification to label the EJB classes and their elements to generate other workpieces - of course, according to "only Configure special circumstances strategy, if you don't write most labels, EJB containers also generate default workpieces.

EJB classes must be marked with metadata to declare their category (session bean, entity beans or mdb), or implement a sub-interface (sessionbean, entitybean or messageDrivenbean) of the Javax.EJB.EnterpriseBea interface (SessionBean, EntityBean or MessageDriveNbean). The usual approach is to use metadata annotation, available labels include @ stateless, @ stateful, @ messagedriven, and @entity. If the category is declared through the metadata, the EJB class does not need to implement a callback method defined by the EnterpriseBean sub-interface; and if these callback methods are implemented, the EJB container will call them in a manner specified by the EJB 2.1 specification.

Below is an EJB class code code with a state SESSION bean:

@Stateful public class cartBean imports shopPingCart {

PRIVATE FLOAT TOTAL;

PRIVATE VECTOR ProductCodes;

Public Int SomeshoppingMethod () {...};

...

Ejbremove () {...};

}

It can be seen that the only difference between this class and the ordinary Java Bean is only the "@stateful" labeling at the beginning. In addition to the EJB container, this label will be directly ignored and will not have any effect. In addition, the CartBean class implements the ejbremove () method of the SessionBean interface declared, and the EJB container calls the method when the component is removed; if this method is not implemented, the component is removed only by default. According to the principle of "targeting interface program", the session bean and MDB should have a business interface (Entity Bean does not have to be because it is more simply, and a java bean consisting of a set of getter / setters). MDB's service interfaces are usually determined by the message type (such as using JMS, MDB's service interface should be javax.jms.MessageListener), the most worthy of concern is the service interface of session beans. Since the session bean usually represents the implementation of business logic, discuss its business interface is also the most meaningful.

The EJB class business interface does not need to inherit any interface from the EJB specification. In other words, the business interface is completely Poji (Plain-Old Java Interface, ordinary Java interface). The business interface can be designed with the EJB class, and is implemented by the EJB class or automatically from the EJB class. An EJB class can implement multiple service interfaces.

The business interface will be default the local interface (equivalent to using @local annotation), developers can use the @Remote label to declare their remote interface. If the EJB class implements multiple business interfaces, each business interface must explicitly use @ local, @ remote or @WebService to marke a declaration of your access. Below is a state of stateless session beans and its business interface sample code:

/ *

* The Bean Class Implements The Calculator Business Interface:

* /

@ Stateless public class calculatorBean imports Calculator {

Public Float Add (int A, int b) {

RETURN A B;

}

Public Float Subtract (int A, int b) {

Return A - B;

}

}

Public interface Calculator {

Public Float Add (Int A, INT B);

Public Float Subtract (int A, int b);

}

If the EJB class does not implement any interface, the container will automatically generate a service interface for it. In this case, the name of the EJB class must be the end as the "bean", "Impl" or "EJB", and the generated service interface name will remove these suffixes (such as CartBean class generated service interface name CART). If the EJB class does not use the @businessMethod annotation to label any method as a business method, the automatically generated service interface will contain all public methods in the EJB class. The following sample code is equivalent to the previous paragraph, but the service interface will be automatically generated by the EJB container:

/ *

* This class definition causes the Calculator

* Interface to be generated as a local business interface.

* This Interface will Have The Methods Add and Subtract.

* /

@ Stateless Public Class CalculatorBean {Public Float Add (int A, int b) {

RETURN A B;

}

Public Float Subtract (int A, int b) {

Return A - B;

}

}

The business interface can declare an exception of any type, but the implementation of the business method should not throw a java.rmi.RemoteException, even if the business interface is labeled @Remote or @WebService is not possible. If the network protocol level is actually appeared, the container will throw an EJBEXCEPTION and package the RemoteException.

Moreover, although a service interface type is obtained, the client can still enforce the session bean object into a traditional EJB interface (EJBOBJECT or EJBLOCALOBJECT) because the container expands the business interface. For example, the following code is feasible:

Calculator Calc; // Calculator is a session bean service interface

EjBlocalobject EJBO = (EjBlocalobject) CALC;

Context environment and dependency injection

Any component cannot be existed from the context environment, EJB is no exception. In version 2.1, the EJB container does not do more management for the context environment of the component. If an EJB needs to use another EJB, it must find and create an instance of the latter through JNDI. In EJB 3.0, the container has put more attention to component context management. The EJB can rely on the EJB container to rely on the EJB container by means of a metadata annotation, and the context environment you need to access is injected through the member variable or setter method; can also get a new lookup () method through the Javax.ejb.ejbContext interface to get the container Any EJB or resource in the middle. Readers who are familiar with the Spring frame may have to remember such a design memory - yes, like BeanFactory design. From a conceptual, the component management section of the EJB 3.0 container is not born with Spring. Let's take a look at some of the details.

EJB 3.0 allows two forms of dependency injection: member variable injection and SETTER method injection. Setter method injection (that is, Type 2 IOC [2]) we often say; if a member variable is directly declared as public, plus appropriate label, EJB 3.0 container will also rely on it . That is, the following two dependent implantation methods are equivalent:

// member variable injection

@Ejb public shoppingcart myshoppingcartbean;

// setter injection

@Ejb public void setMyShoppingCartBean (ShoppingCart ACART) {

Myshoppingcartbean = acart;

}

If you need to inject an EJB component (more accurately, a session bean), you should use the @ejb annotation; if you need to inject external resources in the EJB environment (such as database connection, transaction object, etc.), Use @Resource annotations. When using these two labels, you also need to specify the name (Name property) of the resource (or EJB) to be injected, the JNDI full name (JNDINAME attribute), to inject the EJB service interface (BusinessInterface property), but most of this can Automatically estimate a reasonable default value according to the program code. If all information uses the default, then the contact name can not be distinguished, and the @Inect is annotated. For example: @Inect public datasource mydb;

@Inect public shoppingcart;

In addition to EJBCONText, EJB 3.0 also specifies a global context environment entry class: javax.ejb.context. Its statement and usage are as follows:

Package javax.ejb;

Public class context {

Public Object getObject (String Objectname) {...}

PUBLIC STRING [] getObjectnames () {...}

Public Boolean isobject (String Objectname) {...}

}

Context context = new context ();

With this entry object, all resources and components in the EJB environment can be accessed.

Entity Bean and O / R Mapping

In the EJB 3.0 specification, the Entity Bean is a lightweight domain object. Here, "Lightweight" means: When using the EJB 3.0 API, the Entity Bean does not need the HOME interface or any component interface, the most important (usually the only) workpiece is the Entity Bean class itself - this is a concrete class Not (like EJB 2.1 CMP) an abstract class.

CMP has two strategies when persistent Entity bean: if the Access property of the @entity annotation is specified as Property (this is also the default value), follow the java bean naming rules, persistent all the bean properties (labeled @ @ @ @ @ Except for the property of Transient; if the Access property is specified as Field, the container directly accesses the member variable of the entity bean, which will not be transient, and is not labeled as a member variable marked @Transient as a persistent field. It should be noted that if the second policy is adopted, the member variables of the persistence field must be protected or public; if the first policy is used, the setter and getter that requires persistent Bean properties must be protected. Or PUBLIC. In my opinion, the first policy (persistent according to Java Bean property) is more reasonable, and it is more easily understood.

Each Entity Bean must have a unique identifier (or primary key). This primary key must be one of the following types: Java native type (such as char, int), original type of packaging type (such as char, integer), String Type, or a primary key class consisting of multiple fields that meet the above types. If you use a custom primary key class, you must override this type of equals () and havehcode () methods. As a lightweight domain object, the creation of EJB 3.0 Entity Bean does not need to be as large as the previous context, and the user can directly New out an Entity Bean and assign it. At this time, the Entity Bean is just a normal Java Bean, and has not yet lasteded the unique identifier, nor does it associate with the persistence context. Subsequently, the user can associate the Entity Bean with the persistence context with the EntityManager and give it unique identifier. EntityManager is a persistent management interface for all Entity Beans, and any Entity Bean's crud and query operation must be done by it. Readers who are familiar with Hibernate [3] will feel well to this interface because it is very similar to Hibernate's session interface. Below is the main method in the EntityManager interface:

Package javax.ejb;

Public interface EntityManager {

Public Void Create (Object Entity);

PUBLIC T Merge (t entity);

Public Void Remove (Object Entity);

Public Object Find (String EntityName, Object PrimaryKey);

Public T Find (Class EntityClass, Object PrimaryKey);

Public void flush ();

Public Query CreateQuery (String Ejbqlstring);

Public Query CreateNamedQuery; String Name;

Public Query CreatenativeQuery (String Sqlstring);

Public void refresh (Object Entity);

Public void evic (Object Entity);

Public Boolean Contains (Object Entity);

}

Compared to EJB 2.0, EJB 3.0 Entity Bean's largest improvement may be supported by inheritance. An Entity Bean class can inherit another Entity Bean class, and EJB 3.0 also supports the polymorphic association and polymorphic query of Entity Beans. When using inheritance, the ID field of the subclass and the parent class must be the same.

When mapping a class system with inheritance relationships into a database table structure, the optional mapping scheme has the following:

"A type of system with a table" policy: Map all fields in the class system (regardless of the parent class or subcategory) to the same table. The advantage of this is that the access is fast, the polymorphic query is convenient, and the disadvantages have more redundant fields, and space waste is large.

"Each class table" policy: Map all the fields of each class (whether from the parent or itself) to a separate table. This is not wasted in space, and reads and writes / update operations are also very fast, but the ability to polymorphize queries is very poor, you need to use the Union query or subquery to achieve polymorphism.

? "Connecting Sub Class" Policy: Map each class (whether abstract class or specific class) itself is mapped to a separate table. This is very convenient to make a polymorphic query, and there is no space for waste, but the operational performance of the creation and query is low. Once a normal query requires one or even several times (depending on the number of inherits), the connection operation can be completed. EJB 3.0 only requires the application server to support the "A Table of A Table" mapping policy. The other two mapping strategies are optional in version 3.0, but may become a necessary feature in version 3.1.

Query interface and EJB QL

In EJB 2.1, Entity Bean's query capability is one of the characteristics of the disease. The "EJB Design Mode" of Floyd Marinescu actually has "JDBC forreading" (JDBC forreading), and the Entity Bean is weakly visible.

The query function of EJB 3.0 Entity Bean is mainly implemented through the Query interface. It can be seen from the EntityManager interface mentioned earlier, there are three ways to create a Query object:

? Call the CreateQuery method, create a query as a parameter with an EJB QL statement;

? Call the CreateNamedQuery method, create a named query;

• Call the CreateNativeQuery method and create a query as a parameter with a native SQL statement.

That is, EJB 3.0 Entity Bean can not only perform EJB QL queries, but also perform native SQL statements. Query interface supports the necessary functions such as page restrictions, we do not list its full definition, below is an example of using it:

Public List FindwithName (String Name) {

Return em.createquery

"SELECT C from Customer C Where C.Name Like: CustName")

.SETPARAMETER ("Custname", Name)

.SETMAXRESULTS (10)

.listresults ();

}

Name query (named query)

In the O / R mapping framework of EJB 2.1 CMP and Hibernate, the naming query is usually in the form of a method: findbyloginname () method represents "Press Login Name Query", the FindByrole () method represents "inquiry by role", etc. . In EJB 3.0, naming queries are fully declared using metadata, and there is no additional approach. For example, the following is a naming query:

@Namedquery

Name = "FindAllCustomerswithname",

QueryString = "SELECT C from Customer C Where C.Name Like: Custname"

)

The code using this named query is as follows:

@Inject public EntityManager em;

Customers = em.createnamedQuery ("FindAllcuSwithname)

.SetParameter ("Custname", "Smith")

.listresults ();

EJB QL is an important tool for entry Bean queries. In EJB 3.0, EJB QL has great enhancements and enhancements, has become a truly available query language. Below, let's take a look at the main features of EJB 3.0 QL. ? Batch operation. The new EJB QL has added a batch update / delete operation. It should be noted that batch operations can only be performed for the Entity Bean of the same type (and its subtype). The QL example of bulk update / deletion is as follows:

Delete

From customer c

WHERE C.STATUS = 'Inactive'

Update Customer C

Set C.Status = 'outstanding'

WHERE C.BALANCE <10000

• Join. EJB 3.0 QL supports an inner join and an Outer Join operation. The connection can be performed according to the properties of the object itself, or can be performed according to the attributes of the associated object. For example, the following two connection statements are legal:

Select C from Customer C, Employee E Where C. Hatsize = E.SHOESIZE

Select C from Customer C Join C.Orders Where C.Status = 1

Projection. EJB 3.0 QL can not only query the entity bean. In fact, when you queries with EJB 3.0 QL, you can only take out the field you care, and you can even combine multiple Entity Beans's fields, which is the "projection" capability. For example, the following query:

Select C.ID, C.Status

From Customer C Join C.Orders O

WHERE O.COUNT> 100

A List object will be returned, each element is an Object array, and the latter represents a field in the projection. If you have prepared a Java object to save the results of the projected query, you can also create Java objects directly in the QL statement, for example:

Select New CustomerDetails (C.ID, C.Status, O.count)

From Customer C Join C.Orders O

WHERE O.COUNT> 100

Note that the Java object to be created at this time must have a corresponding constructor, otherwise the NosuchmethodeXception will be thrown.

? Subquery (SUBQUERY). In the WHERE statement, subqueries can be used, with subquery results as the condition of WHERE queries, for example:

Select GoodCustomer

From Customer GoodcuStomer

WHERE GoodCustomer.balance <(

SELECT AVG (C.Balance) from Customer C)

Polymorphism Query. EJB 3.0 QL automatically supports polymorphism. If the Entity bean type specified in the FROM statement is a base class, all subclasses of this type will be within the query.

? Name Parameter. EJB 3.0 QL Allows the named parameters, named parameters are represented by a colon (:) prefix, which will be dynamically binded during runtime. E.g:

SELECT C

From customer c

Where c.status =: stat

When using this QL statement, the Query object must assign a stat to the STAT parameter.

? Other functions. Other functions that can be used as query conditions in the WHERE statement include: Upper, Lower, Trim, POSITION, CHARACTER_LENGTH, CHAR_LENGTH, BIT_LENGTH, CURRENT_TIME, CURRENT_DATE, CURRENT_TIMESTAMP, and more.

Readers who are familiar with Hibernate are not difficult to see, EJB 3.0 QL and Hibernate QL are very similar - when they were present, Ms. Linda Demichiel in the EJB expert group was simply used in the THESERVERSIDE year. Before the Reference Realization of EJB 3.0, learning Hibernate QL should not be beneficial to familiar EJB 3.0 QL.

summary

This article examines some of the new features of the first preview version of EJB 3.0 specification with a closer perspective. Due to more attention to the new features that differ from EJB 2.1, this paper may not be sufficient to help readers form an overall impression of EJB 3.0, interested readers can refer to "programmer" 2004 "Analyzes EJB" article. In addition, the reference is only the first preview version of the EJB 3.0 specification, in the next year, the technical details of this specification may also change, and readers cannot be observed.

EJB 3.0 will be the largest change in the history of EJB, fully draw the Open Source Community - Especially Spring, Hibernate and other excellent projects - the experience makes EJB to become the potential of technology mainstream. In view of this, although the norms of EJB 3.0 need to shape next year, the application server support needs a longer time, but now it is now in depth, it is not too early. A new era of Java is coming soon, are you ready?

[1] About the in-depth discussion of dependency injection, see "Programmer" 2004 No. 3 "IOC container and Dependency Injection mode".

[2] See "Programmer" in 2003, No. 12 "Inverse Control".

[3] About Hibernate in-depth discussion, see "Hematology Database" serialized in "programmers" from 9th to 11th period of 2003.

转载请注明原文地址:https://www.9cbs.com/read-92528.html

New Post(0)