Richard Monson-Haefel Openejb Chief Designer June 2000
The new EJB 2.0 specification is more than just a new stage of issue, which has joined many striking changes, including some changes in the CMP component model and a new bean type, which will enhance your development application Flexibility and portability. Please take the lead in understanding the function of this new specification. This month has released its public draft.
Enterprise JavaBeans 2.0 released on June 2 is not only a phased release, but also a new version of this specification. The entire specification has more than 500 pages, which is 200 pages (66%) than the previous EJB 1.1 specification. The most important changes in this specification are changes made to the persistent (CMP) managed by the container, and introduced a new bean type, namely MessageDriveNbean.
A large number of changes in EJB 2.0 are concentrated in a definition of a new CMP component model. It is completely different from the old CMP model because it introduces a new member, a persistence manager, and introduces a new way to define the field of container management, and the relationship between these fields and other beans and slave objects.
The introduction of MessageDriveNbean (Message Bean) is also very important. The message bean reflects the JMS (Java Message Service) integration to create a new BEAN type, which is designed to process asynchronous JMS messages. This kind of inspirable BEAN provides a component model for JMS clients, allowing them to deploy them into a rich and robust environment of the EJB container system.
There is also a small number of other changes to this specification. Although these other changes are also important, they mainly involve more stringent to eliminate polysemous and make these components with higher portability. This article focuses on the new CMP and message bean component model introduced in EJB 2.0.
I will provide a few specific examples, so the reader should be easy to keep up and understand it. However, EJB beginners may find that this material is more difficult because it assumes that the reader has a basic understanding of EJB. For more information on EJB, see Resources.
The persistence of persistent container management of container management has changed fundamental changes in EJB 2.0. In EJB 2.0, the persistence manager automatically processes the persistence of the CMP entity bean at runtime. The persistence manager is responsible for mapping the entity bean to the database according to a new BEAN persistent manager contract called an abstract persistence program. In addition, persistence managers are also responsible for implementing and implementing a variety of findings, which are based on a new query language called EJB QL.
It is important to note that the product that meets the EJB 2.0 specification must support the EJB 1.1 CMP model, and support the new EJB 2.0 model. Although these two models are not compatible, in order to ensure backward compatibility, the EJB 1.1 model must be supported.
Abstract Persistent Programs In order to understand how abstract durability work work, and why is it important, I will quickly review how to handle CMP in EJB 1.1, then discuss how to define it in EJB 2.0.
The CMP model in EJB 1.1 is in EJB 1.1, the Bean developers are responsible for declaring the Persistent field of the BEAN class as the Java basic type or sequential type. The following example shows an Employee enterprise bean class, which is defined by EJB 1.1 with several CMP fields:
// Employee Bean class
Public Class Employeebean IMPLEMENTS
Java.ejb.entityBean {// instance field
EntityContext ejbcontext;
// Container management field
Public Int Idness;
Public string firstname;
Public String lastname;
Public Double Salary;
Public Address Address;
Public Integer Ejbcreate (int ID, String Fname,
String lname) {
Identity = ID;
FigStName = fname;
Lastname = lname;
Return NULL;
}
...
}
// Address from the genus
Public class address imports serializable {
Public String Street;
Public string city;
Public String State;
Public String Zip;
}
When the relational database is used for persistence, the basic fields such as Identity, FirstName, LastName and Salary are easy to persist, as they are well mapped to SQL types, such as Integer, CHAR, and DOUBLE.
In EJB 1.1, the XML deployment descriptor of the CMP bean provides a CMP-field element to identify persistence fields in this bean class (the fields managed by the container management). As shown below, the cmp-field element is used to distinguish the fields written to the database and the fields that do not write to the database. For example, the EJBContext field is not included in the list of fields managed by the container, so it is not a persistent field.
...
...
...
The container provider provides a tool to map the Persistence field of the BEAN to the columns in the database table, usually each bean corresponds to a table. However, the type of semicamination, such as Address, is more difficult to persist. In EJB 1.1, there is no standard method to map sequentially to the relational database. Although the Address class has its own field set, the XML deployment descriptor does not provide a mechanism to map these fields to the database. In most cases, it is desirable to persist in a database table in a binary type (such as address) as a binary type (sometimes referred to as a BLOB type). This problem has also become serious because the data scheme of the entity bean is gradually complex. For example, Employee Beans may have multiple sub-objects similar to Address, such as Benefits and JobPosition. These sub-objects are called slave objects, which can form complex object maps across several tables in a relational database. In addition, the CMP in EJB 1.1 is largely insufficient to persist with other beans. In EJB 1.1, if a bean is ready to maintain a relationship with another bean, the container will automatically use the primary keyword or handle as a link. The relationship with some other beans may be two-way, or to rely on some fields that are not easy to use by the master keyword or handle, in order to maintain the relationship with such beans, the above method has proven to be a far Unmine mechanism.
EJB 2.0 CMP Model In EJB 2.0, the new contract between the CMP entity bean and the Persistent Manager enables you to define more complex and more portable relationships in entity beans, including BEAN and Bean The relationship between the bean and the slave object, even between the object and the slave object.
Persistent Manager is new to Enterprise JavaBeans deployment procedures. Container manufacturers, or vendors who have a persistence of specific databases will provide this persistence manager. Its idea is to separate the mechanisms used to manage Bean relationships from the container, and the container is only responsible for managing security, transactions, and resources. This separation of this responsibility makes different persistence managers work with different containers. It also makes the entity bean between different EJB vendors and is more portable between various persistent managers.
If you use or learn THOUGHT Inc., you can automatically generate BMP (BEAN-managed persistence) Bean's product Cocobase for EJB 1.1 containers, you are more familiar with how your persistence manager tool is working. Cocobase generates all database access logic for BMP Beans from the object to the mapping information provided by the Bean deployer. In EJB 2.0, the persistence manager can generate a mapping of the CMP entity to the relational database based on the information provided by the deployment descriptor, the work of the BEAN's abstract persistence scheme and the deployer. However, persistence managers are not limited to relational databases. It is also possible to develop persistence managers for object databases and legacy systems and ERP systems (such as SAP).
In order to separate the persistence manager from the container, the contract between the bean and the persistence manager must be defined. This contract exhibits in a new abstract persistence program. This protocol is defined by a set of new XML elements in the deployment descriptor and a set of code idios in the CMP entity bean. In EJB 2.0, the CMP bean class is declared as an abstract class. Its persistence field and relationship field are access to the abstract read method and write method, and the method of these two methods is mapped to XML deployment descriptor. Specific elements in the middle.
When deploying this bean, you will use a Persistent Manager tool to specifically implement this abstract bean class and its dependent object class according to the XML deployment descriptor and bean class. Specific implementations will include data access code, which will actually read and write in the database status at runtime. At runtime, the container uses subclasses generated by Persistent Manager tools without using an abstract class defined by the bean provider. Inheritance hierarchy of the bean class
In order to make the discussion more enrichment, an example of a CMP entity is provided, which more specifically explains how abstract persistence schemes work.
One example CMP entity in EJB 2.0 In EJB 2.0, the entity bean managed by the container is defined as abstract, and its persistence field is not directly defined in the bean class. Alternatively, an abstract persistence scheme has been developed, allowing the Bean provider to indirectly declare the persistence field and bean relationship. Here is an example of the Employee Bean, which uses a new abstract persistence solution. Note that any persistence fields are not declare in this bean class.
Public Abstract Employeebean IMPLEMENTS
Javax.ejb.entitybean {
. // instance field
EntityContext ejbcontext;
// Container management persistence field
Public Abstract Void SetIdentity (int
Identity;
Public Abstract Int getIdientity ();
Public Abstract void setFirstname (String
Firstname);
Public Abstract string getfirstname ();
Public Abstract void setlastname (String
Lastname);
Public Abstract string getlastname ();
// Container management relationship field
Public Abstract Void
SetContactInfo (ContactInfo Info);
Public Abstract ContactInfo
GetContactinfo ();
...
}
In this bean's XML deployment descriptor, abstract persistence regimen declares all fields and various relationships of container management.
...
...
...
Entity>
enterprise-beans>
...
dependent>
EMPLOYEE-HAS-ContactInfo
EJB-RELATIONSHIP-ROLE-NAME>
role-source>
CMR-Field>
EJB-RELATIONSHIP-ROLE>
ContactInfo_belongsto_employee
EJB-RELATIONSHIP-ROLE-NAME>
role-source>
EJB-RELATIONSHIP-ROLE>
EJB-RELATION>
rateships>
The XML elements used to describe the relationship of container management may become very complicated because they must handle the correspondence and direction of various relationships (one-way or bidirectional). The above code segment description, in order to describe the simple relationship between the bean and its dependent object classes, what you need. Although even simple relationships will be converted to lengthy XML, all of these elements are required so that the persistence manager can map complex object maps into the database.
Although the XML element of an abstract persistence scheme for defining the CMP bean is the main problem in the CMP in EJB 2.0, the XML example is no longer provided for the sake of brevity. Alternatively, this article will be purely relying purely on the abstract idioms that must be used in the bean class, indicating the basic concepts behind the CMP in EJB 2.0. These code idioms are used with relationship elements in the XML deployment descriptor and are defined by the latter, so you cannot only have one without another, but they are easier to understand than the XML part of the program.
In addition to the XML element, the abstract persistence option also defines a set of idioms that will inevitably use when declaring the Bean class and its related objects. The method used to access and modify the field is strictly defined, requiring the SET
Public Abstract Class ContactInfo {
// Home address information
Public Abstract Void SetStreet (STRING Street);
Public abstract string getstreet ();
Public Abstract Void SetState (String State);
Public abstract string getState ();
Public Abstract Void Setzip (String Zip);
Public Abstract string getzip ();
Public Abstract Void setomePhone (String phone);
Public Abstract string gethomephone ();
// Work address information
Public Abstract void setworkphone;
Public Abstract string getWorkphone ();
Public Abstract Void SeteMail (String email);
Public Abstract string getemail ();
...
}
The dependent object exists with the existence of the entity bean, and aborted with the abortment of the entity bean, which is the key to understand the relationship between the object and the entity bean. The dependent object is included in a specific entity, so deleting this entity will cause the slave object to be deleted. In terms of terms of the relational database, sometimes this is called cascading deletion.
Dependent objects, such as ContactInfo, in the relational field. The slave object class with the relationship between the entity bean is called the slave object class. EJB client applications can never access the slave object class directly; this class cannot be used as a parameter or return value in the remote or local interface of the BEAN. The dependent object class is only visible to the Bean class.
The dependent object class is not suitable as a remote parameter type because they have a close relationship with the bean's persistence logic at runtime. Persistent Manager extends an abstract slave object class to provide an implementation that can be used to manage the persistence of beans at runtime. In addition, the abstract persistence plan is also modeling data - rather than modeling of business concepts represented by enterprise-class beans - so as a design strategy, abstract persistence programs hide the EJB client It is meaningful.
For example, in addition to the simple address information required by the client client, there is many other information in addition to the simple address information required for the Bean client. Although you can use the subordinate objects in the abstract persistence scheme (it hides the Bean client), you have to use other objects to actually express these data to the client. Below is an example, explaining how to hide the EJB client hide the ContactInfo dependent object. In this example, the address information is exposed by the Address object developed in the example of EJB 1.1.
// Employee Bean remote interface
Public interface Employee Extends javax.ejb.ejbobject {
Public Address GethomeAddress (); Public Void SetHomeAddress (Address Address);
Public int getidentity () throws remoteException;
Public void setfirstname (String firstname) throws
RemoteException;
Public string getfirstname () throws remoteexception;
Public void setlastname (String Lastname) Throws
RemoteException;
PUBLIC STRING GetLastname () THROWS RemoteException;
}
// Employee Bean Bean class
Public Abstract Employeebean IMPLEMENTS
Javax.ejb.entitybean {
...
Public Address gethomeAddress () {
ContactInfo info = getContactInfo ();
Address Addr = new address ();
Addr.Street = info.getstreeet ();
Addr.city = info.getcity ();
Addr.State = info.getState ();
Addr.zip = info.getzip ();
Return addr;
}
Public void setHomeAddress (address addr) {
ContactInfo info = getContactInfo ();
Info.SetStreet (Addr.street);
Info.getCity (addr.city);
Info.getState (Addr.State);
Info.getzip (addr.zip);
}
....
// Container management relationship field
Public Abstract Void SetContactInfo (ContactInfo)
INFO);
Public Abstract ContactInfo getContactInfo ();
...
}
Although the relationship field of container management does not expose to the client, you can still use the persistent field management from the remote interface. Note that the persistence field used to access the Firstname and LastName is used in a remote interface.
A bean may have a variety of different relationships between the various slave object classes, which are defined by the correspondence and direction of this relationship. BEANs can have a pair and one-to-one relationship between the slave object class. For example, Employee Beans may have only one Benefit slave object class, but there may be many ContactInfo slave object classes.
Public Abstract Employeebean IMPLEMENTS
Javax.ejb.entitybean {
...
Public Abstract Void SetContactinfos (Collection
Addresses;
Public Abstract Collection getContactInfos ():
Public Abstract void setBenefit (Benefit Benefit);
Public Abstract Benefit getBenefit ();
...
}
A multi-relationship with the slave object class can be represented as a java.util.collection type, or it can be represented as an av.util.set type (Note: in subsequent versions of this specification, java.util.map and java.util .List is considered an additional return type), and a pair of relationships with the slave object uses the type of the slave object. Entity Beans can also define the relationship with other entity beans. These relationships can be one-to-one, one or more or more. For example, Employee Beans may have many sub-stage beans, and there is only one paired bean. The following code segments use the abstract persistence scheme method idios, how to model these relationships. In this app, both child beans and paired beans are behaving as Person Bean.
Public Abstract Employeebean IMPLEMENTS
Javax.ejb.entitybean {
...
Public Abstract Void Setspouse (Person Manager);
Public Abstract Person getspouse ();
Public Abstract Void SetChildren (Collection
Family);
Public Abstract Collection getChildren ();
...
}
A multi-relationship with another bean is expressed as a java.util.collection type or a java.util.set type, and one-on-one relationship uses the Remote interface type of this bean.
The dependent object itself can have one-to-one, one-to-many and multi-to-many relationships between other slave objects in the same bean. In addition, the dependent object can have one-to-one, one-to-many relationship with other entity beans. The following example shows how the Benefit slave object class has a one-to-one relationship between the Salary slave object (a compensation calculation program), and how the Investment Bean has a pair of relationships.
Public Abstract Class Benefit {
Public Abstract Void Setsalary; Salary Salary;
Public Abstract Salary GetSalary ();
Public Abstract Void SetINVESTMENTS (Collection
Investments);
Public Abstract Collection GetInvestments ();
}
At deployment, deployers will use the Persistent Manager tool to specifically implement this bean class and its own class. These specific implementations will maintain a variety of relationships at runtime and synchronize the status of each bean instance. The container will manage persistence instances at runtime to provide a robust environment with automatic access control and transaction control.
BEAN can also define the value of the slave object, which is a serialized object, such as the Address object in the EJB 1.1 example. These values have become lasting by serialization, they do not form a relationship with beans - they are strict vessel management persistent fields.
A contract has also been defined between the container and the persistence manager, allowing the persistence manager to obtain the handle of the transaction, and accesses the database connection pool managed by the container. This contract is slightly loose, and it needs to make it more stringent in the future, but it is the basis for the persistence manager to transplant the EJB container. The details of the contract between the containers and persistence managers have exceeded the scope of this article.
In addition to the definition of persistence by abstract durability, EJB 2.0 provides a new query language to explain how the persistence manager should implement various lookup methods in the CMP.
EJB Query Language EJB Query Language (EJB QL) specifies how the persistence manager should implement various lookup methods defined in the local interface. EJB QL is based on SQL-92, which can be automatically compiled by the persistence manager, so that entity beans have higher portability and is easier to deploy. EJB QL and Find Method EJB QL statements are declared in the deployment descriptor of entity beans. It is very simple to use EJB QL. As an example, the local interface of Employee Bean can be declared as follows:
Public Interface Employehome Extends Javax.ejb.ejbhome
{
...
Public Employee FindByPrimaryKey (Integer ID)
THROWS RemoteException, CreateException;
Public Collection FindByzipcode (String Zipcode)
THROWS RemoteException, CreateException;
Public Collection Findbyvent (String
InvestmentName)
THROWS RemoteException, CreateException;
}
After a given local interface definition, you can use EJB QL to specify how the persistence manager performs a lookup method. Each entity bean must have a FindByPrimaryKey () method. The query required to perform this method is obvious - finding the bean in the database using the (one or several) fields of the primary key, so there is no need for any EJB QL statement.
The FindByzipCode () method is used to get all Employee Beans with a postal code. This will express it using the following EJB QL in the deployment descriptor.
From contactinfo where contactinfo.zip =? 1
This statement is essentially "all EMPLOYEE beans that choose its postal code equal to ZIPCode parameters".
In the EJB QL statement used to find methods, you don't need to use the SELECT clause to indicate the content to be selected. This is because the lookup method will always select the same remote reference as its own bean type. In this case, you can think that the selection statement will return all references to remote Employee Beans.
If the various lookup methods are deployed in the same EJB-JAR file, and there are actual relationships with navigable, then these lookup methods can even get into the abstract persistence scenarios of other beans. For example, the FindbyNVestment () method will request the lookup query to navigate from Employee to the abstract persistence plan of the investment bean. Declare to express this EJB QL statement that this lookup operation is shown below.
From element in benefit.investments where element.name
=? 1
The above statement is to say: "Select all such EMPLOYEEEEEEee Beans: The profit slave object contains at least one investment bean, and its name is equal to the invstmentName parameter of the FindbyNVestment () method."
EJB QL and Selection Method EJB QL is also used in a new query method called an EJBSELECT method, which is similar to the search method, just it is for BEAN class. This method is not declared in the local interface, so it is not revealed to the client. In addition, the EJBSELECT method returns a larger value of the range, not limited to the remote interface type of the bean itself.
There are two options: EJBSELECT
Javax.ejb.entitybean {
...
// EJBSELECTINETITITITY
Public Abstract Collection
EJBSELECTINVESTMENTSINENTITY (STRING RISK);
// EJBSELECT
Public Abstract Collection
EJBSELECTINVESTMENTS (STRING RISK);
...
}
In the above statement, two selection methods run in different ranges. EJBSelectInvestmentSinerTmentity () is only executed on the current Employee Bean instance, so it only returns to employees' risk investment.
Select Invest from Invest In Benefit.INVESTMENTS WHERE
INVEST.TYPE =? 1
On the other hand, the scope of the EJBSELECT
EJBSELECT
The EJB QL statement for the selection method requires the use of SELECT clauses because they can return a wide range of values.
The new EJBHOME method is in EJB 2.0, entity beans can declare some EJBHome methods to perform operations related to EJB components, but are not dedicated to a bean instance. The EJBHOME method defined in the bean class must have a local method that matches therefrom. The following code illustrates a local method that is defined as the local interface of the Employee Bean. Applycola () method is used to update the salary of all employees based on the growth of the most recent Cola (cost adjustment).
Public Interface Employehome Extends Javax.ejb.ejbhome
{
// Local method
Public void Applycola (double increate) throws
RemoteException;
...
}
ApplyCola () method must have a matching EJBHome method in the bean class, which is declared as ejbhomeApplycola (). The EJBHOMEApplyCola () method is not dedicated to a bean instance, which is globally, so it will use the same COLA for all employees.
Public Abstract Class Employeebean IMPLEMENTS
Javax.ejb.entitybean {
...
// ejbhome method
Public void ejbhomeApplycola (double increase) {Collection col = EJBSELECTALLEMPLOYEES ();
Iterator Employees = col.iterator ();
WHILE (Employees.next ()) {
EMPLOYEE EMP =
(Employee) Employees.next ();
Double Salry =
Emp.Getannualsalary ();
SALARY = Salary (Salary * Increase);
Emp.Setannualsalary (SALARY);
}
}
}
BEAN's developers need to implement EJBHome methods for BMP and CMP entity beans. The CMP implementation may depends to a large extent on global selection statement (as described above) and the Finder method, and the EJBHOME's BMP implementation will use direct database access and bean's Finder method to query data and make changes. .
MessageDriveNbean In EJB 2.0, a basic change to the specification has added a new enterprise-class bean type, namely MESSAGEDRIVENBEAN. MessageDriveNbean is designed to process JMS messages in the network. For many developers, JMS is a new example, so this article will take some time to gradually explain the understanding of JMS, and their usage in EJB 2.0.
What is JMS? JMS is an API that is unrelated to the vendor to access the message transceiver system. It is similar to JDBC (Java Database Connectivity): Here, JDBC is an API that can be used to access many different relational databases, while JMS provides access methods that are also unrelated to vendors to access messaging services. Many vendors currently support JMS, including IBM's MQSeries, BEA's WebLogic JMS Service and Progress SonicMQ, which is just a few examples.
JMS enables you to send messages from a JMS client from a JMS client through a message transceiver service (sometimes called message intermediary program or router). The message is a type object in JMS, consisting of two parts: header and message main body. The header consists of routing information and metadata on the message. The message main body carries the application's data or payload. Depending on the type of payload, you can divide the message into several types, which carry: textMessage, sequential object (ObjectMessage), attribute set (MapMessage), BytesMessage, original StreamMessage, there is a message without payload (Message).
The message transceiver system is asynchronous, that is, the JMS client can send a message without waiting for a response. It can be seen that this is completely different from RPC-based (remote procedure) systems such as reference implementation of EJB 1.1, CORBA and Java RMI. In RPC, a method of the client calls a distributed object on the server. The client is blocked before the method call returns; the client must wait for the method call to end before the next instruction can be performed. In JMS, the client sends a message to a virtual channel (topic or queue), while other JMS clients book or listen to this virtual channel. When the JMS client sends a message, it does not wait for a response. It performs a sending operation and then proceeds to execute the next instruction. The message may eventually forward to a plurality of clients, which do not need to respond. JMS EJB 2.0 in EJB 2.0 supports JMS integration in two ways: as a BEAN available resources, and as a MessageDriveNbean. When JMS is used as a resource, bean using JMS API is the generator or sender of the message. In this case, Bean sends a message to a virtual channel called a subject or queue. On the other hand, MessageDriveNbean is the user or recipient of the message. It monitors a specific virtual channel (topic or queue) and handles messages sent to this channel. In order to better understand the role of message generator and message users, use sessionBean Beans to send a message using JMS, and then use a new MessageDriveNbean to use the same message.
JMS session beans and entity beans as EJB 2.0 resources are RPC-based components, which are an excellent architecture in order to assemble various transactional components. However, in some cases, the synchronous properties of RPCs will become an obstacle, which is why access to JMS APIs in EJB 1.1 as a resource included. With the context named by JNDI environment, Bean can get a JMS factory and send an asynchronous message to the topic or queue (also obtained from JNDI) without waiting for a response. Below is an example of ShoppingCart Bean, which uses JMS to send ORDER's detailed information to the message transceiver topic.
Public class shoppingcartbean imports sessionbean {
// Order details are a serialized object that contains all orders.
Public ORDERDETAIL ORDERDETAIL;
Public void processorder () {
// Processing the logic of the order begins
....
// ... After processing the order, send a message about this order to other systems.
InitialContext jndienc = new
InitialContext ();
// Get JMS factories and theme identifiers using JNDI ENC
TopicConnectionFactory Factory =
JNDIENC.LOOKUP ("Java: Comp / Env / JMS / TopicFactory");
Topic Ordertopic =
JNDieNc.lookup ("Java: Comp / Env / JMS / Ordertopic");
// get a publisher used to send a message
TopicConnection Con =
Factory.createtopicConnection ();
TopicSession session = con.createtopics (false,
Session.auto_acknowledge;
TopicPublisher Publisher =
Session.createPublisher (Ordertopic);
// Send an ObjectMessage to the topic (virtual channel)
ObjectMessage Message =
Session.createObjectMessage ();
Message.setObject (ORDERDETAIL);
Publisher.publish (Message);
C. close ();
}
...
}
In this case, JMS is used to notify additional applications, and the order has been processed. These additional applications are not important for handling orders, but they will benefit because of a notification that has been processed. Such examples include automatically adjusting the inventory system, and can add customers to the sales app in the product catalog mailing list.
Use JMS to enable the bean to publish (send) messages without blocking. Bean does not know who will receive a message because it is sent to a topic (virtual channel) instead of sending it directly to another application. The application can choose to book this topic and receive notifications for new orders. This is possible to dynamically add or delete applications in a virtual channel, resulting in a more flexible system.
Applications for booking order topics will receive notifications for new orders, and applications can use them to handle this notification anywhere. Applications for various topics or applications that receive messages from each queue can be Java applications, EAI systems (for integrated legacy systems and ERP systems) or MessageDriveNbean components, all of them are considered in JMS terms. Is a JMS client.
JMS and MessageDriveNbean Although most JMS vendors provide a message intermediary tool to route messages from the sender to the recipient, the JMS client that builds (receiving) messages is the responsibility of the application developer. In many cases, the application that receives the message must be strong, safe, and quickly and retractable; it needs to be the same as the EJB application.
Since this needs, EJB 2.0 now includes the MessageDriveNbean type, which can use JMS messages, and handle these messages in the same robust, component-based infrastructure, which is very good for session beans. it works. MessageDriveNbean Type (Message Bean) is an enterprise-class bean component that is designed to use asynchronous JMS messages.
In addition to providing the container infrastructure, EJB has another important advantage: concurrency processing. In EJB, a deployed message bean represents a single message user, but this bean itself provides services by many bean instances. Each bean instance can use the message to receive the message. This means that the message bean does not have to use a message as a regular JMS client. The message bean can use the received multiple messages in concurrently, which can achieve much more throughput and much more scalability than the traditional JMS application.
To illustrate the role of the message bean, it has developed a MarketingBean class and deploy it from the order topic to the usage. MarketingBean extracts the ORDERDETAIL object from the message and uses it to add the customer to the appropriate directory mailing list. This is the most exquisite massive mailing system. Below is the definition of the MarketingBean class, this class uses a message published to the order topic.
Public Class MarketingBean IMPLEMENTS
Javax.ejb.MessageDriveNbean {
Public void onMessage (Message message) {
ObjectMessage ORDERMESSAGE =
(ObjectMessage) OrderMessage:
ORDERDETAIL ORDERDETAIL =
(ORDERDETAIL) OrderMessage.getObject ();
Integer Customerid =
ORDERDETAIL.GETCUSTOMERID ();
InitialContext jndienc = new
InitialContext ();
CatalogHome catalogHOME =
(CatalogHome) JNDienc.lookup ("Java: Comp / ENV / EJB / CATALOG");
Iterator productIDS =
ORDERDETAIL.GETPRODUCTSIDS ();
While (ProductIDs.hasNext ()) {
Integer productID =
"In ader).
Catalog cat =
CatalogHome.FindByProductId (ProductID);
Cat.AddcustomertomailingList (Customerid);
}
}
}
Just like a session bean and entity bean, MessageDriveNbean is also a complete enterprise-class bean, but there are still some important differences. The message bean does not have a remote interface or a local interface. This is because the message bean is not an RPC component. It does not have a business method for EJB client calls. Message bean listens to virtual message channels (topic or queue) and send messages sent to this channel using other JMS clients.
Each message bean constitutes a bean class, which implements the MessageDriveNbean interface and an XML deployment descriptor. Below is the definition of the MessageDriveNbean interface, all messages beans must implement this interface.
Package javax.ejb;
Import javax.jms.message;
Import javax.jms.MESSAGELISTENER;
Public Interface MessageDrivenBean Extends
Messagelistener {
Public void OnMessage (Message Message);
Public void ejbcreate ();
Public void ejbremove ();
Public void
SetMessageDrivenContext (MessageDrivenContext MDC);
}
When a message-driven bean is deployed, it is assigned to handle messages in a specific topic or queue. Any message sent by the JMS client (Java application, bean or local client) will forward the message router to the message bean, which is assigned to receive messages from the virtual channel. When a message is sent to a message bean, the EJB container selects an instance of the bean from a pool to handle this message. When the onMessage () method is called when the bean instance is called, it will receive this message in any way it thinks is appropriate. Once this message is used, the message is not transmitted to any other instance of this message bean as long as the transaction is not abnormal. The message bean is similar to the stateless session bean in a certain point, that is, the two beans do not maintain any status between the two requests. Therefore, the message-driven bean is stateless, but just like a stateless session bean, they can also have instance variables, which are maintained during the entire survival of this bean instance.
The last point of the message bean is that it is important to understand that the message used by the bean is not necessarily generated by other beans. Message beans can use messages in any topic or queue provided by Vendors that meet JMS. Messages used by the message can be from other beans (session beans, entity beans, beans), non-EJB Java applications, or even non-Java applications (if their vendor meets JMS). For example, legacy applications may use IBM's MQSeries to send messages to queues, and the message can be used by other legacy applications, can also be used by message beans.
Conclusion Compared to previous specifications, ENTERPRISE JAVABeans 2.0 made some considerable changes. The new CMP model is much flexible than the previous model, which allows various entities to establish models for complex object maps, while providing greater portability of the container. It is urgent to look forward to defining a common query language for finding and selecting operations, and it will also help improve portability.
This new MessageDriveNbean type will help make this powerful message to become an important focus, just like EJB. Messages are an extremely important part of the distributed hybrid calculation, which includes a proof of its importance within EJB.
When writing this article, EJB 2.0 has just been published as a draft, which means that it is still possible before it becomes a final specification. If the change has a significant impact on the materials provided here, I will try to have some comments to this article, but this specification is tending to stabilize, so it is unlikely to have a real major change.
Reference
"A Beginner's Guide to Enterprise JavaBeans," Mark Johnson (JavaWorld, October 1998): Richard Monson-Haefel the EJB developer site, EJBNow.com EJB 2.0, specification Thought of CocoBase IBM's MQ Series BEA's WebLogic JMS Service Progess Sonic MQ
Other articles written by Richard Monson-Haefel:
"Create Forward-Compatible Beans in EJB, PART 1" (Javaworld, December 1999) "Create Forward-Compatible Beans in EJB, Part 2" (Javaworld, Jan 2000) Author Abtrue Richard Monson-Haefel is recently released Enterprise JavaBeans Second Edition author. He is the chief designer of Openejb (Openejb is an Enterprise JavaBeans 2.0 container for open source), and he has provided consultation with Enterprise Javabeans, Corba, Java RMI, and other Java programs as designers. Monson-Haefel also maintains a website for people to discuss Enterprise JavaBeans and related distributed computing technologies. You can contact Richard Monson-Haefel via richard.monson-haefel@javaworld.com.