Sender: TWOTWO (Juju Joining Honey), News District: Java
Title: Comprehensive study EJB 2.0
Sending station: Listen to Yu Xuan (August 16, 2001 10:58:06 Thursday), station letter
JB 2.0 specification is more than just a new phase of issue, it has added many leading changes.
Move, including some changes in the CMP component model and a new bean type, they will enhance you
Flexibility and portability when you send applications. Please take the lead in understanding the function of this new specification, this month has been released this month.
Open draft.
Enterprise JavaBeans 2.0 released on June 2nd is not only a phased release, but also
A new version of this specification. There are more than 500 pages throughout the specification, 200 more than the previous EJB 1.1 specification.
Page (66%). The most important changes in this specification are changes made to the persistence (CMP) of container management,
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
The CMP model, because it introduces a new member, a persistent manager, and introduces a new one.
Ways define fields of container management and define the relationship between these fields and other beans and slave objects.
The introduction of MessageDriveNbean (Message Bean) is also very important. Message bean reflects
JMS (Java Message Service) integrates with EJB to create a new BEAN type
It is designed to handle asynchronous JMS messages. This new BEAN for this exciting bean is JMS client.
A component model allows 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 important, they are mainly involved.
And make this specification more stringent in order to eliminate polysemous and make these components with higher portability. This episode
The new CMP and message bean component models introduced in EJB 2.0 are discussed.
I will provide a few specific examples, so the reader should be easy to keep up and understand it. However, EJB beginners
It may be found that this material is more difficult because it assumes that the reader has a basic understanding of EJB. related
For more information on EJB, see Resources.
Container management persistence
The persistence of container management has undergone fundamental changes in EJB 2.0. In EJB 2.0, persistence manager
Automatically handle the persistence of CMP entity beans at runtime. Persistent Manager is responsible for according to a kind
The new Bean Persistence Manager contract with the lasting program, maps the entity bean to the database. In addition
The persistence manager is also responsible for implementing and implementing a variety of findings, these lookup methods are based on one
New query language of EJB QL.
Note that the following facts are important, that is, the product that meets EJB 2.0 specification must support EJB 1.1
The CMP model can support new EJB 2.0 models. Although these two models are not compatible, in order to protect
If the certificate is compatible, you must support the EJB 1.1 model.
Abstract durability
In order to understand how abstract persistence programs work, and why is it important, I will quickly review it.
How to deal with CMP in EJB 1.1, then discuss how to define it in EJB 2.0.
CMP model in EJB 1.1
In EJB 1.1, the Bean developers are responsible for declaring the Persistence field of the Bean class as the Java basic class.
Type or serialized type. The following example shows an Employee enterprise-class bean class, which is EJB
1.1 Defined, with a few 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;
}
Basic fields such as Identity, Firstname, Lastname, when the relational database is used for persistence
Salary is easy to persistence because they are well mapped to SQL type, such as Integer, Char
And Double.
In EJB 1.1, the XML deployment descriptor of CMP bean provides a CMP-field element to identify this.
Persistent fields in the bean class (the field of container management). As shown below, the CMP-Field element is used to zone
Divide the fields of 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, it is not a persistent field.
...
...
...
The container provider provides a tool to map the BEAN's persistence field to the column in the database table,
Always correspond to a table in each bean. However, the type of semicamination, such as address, is more difficult to last
. 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, but the XML deployment descriptor does not provide a mechanism to map these fields to the database. In most cases, people expect to be semicaminated objects (such as
Address) As a binary type (sometimes called BLOB type) persistence into a database table.
This problem has also become serious because the data scheme of the entity bean is gradually complex. E.g,
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 complexity across several tables in relational databases.
Object map. In addition, the CMP in EJB 1.1 is largely insufficient to persistence and other beans.
system. 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 depends on some fields that are not easy to use the master keyword or handle, in order to keep this
The relationship of Bean has proven to be a long-term mechanism.
EJB 2.0 CMP model
In EJB 2.0, the new contract between the CMP entity bean and the persistence manager allows you to be in the entity
Beans define more complex, transplantable relationships, including Bean and Bean, bean
The relationship between the slave object and even the object and the slave object.
Persistent Manager is new to Enterprise JavaBeans deployment procedures. Container manufacturer, or special
Vendors that are longer than a specific database will provide this persistent manager. Its ideas will be used in tubes
The mechanism of the BEAN relationship is separated from the container, and the container is only responsible for managing security, transactions and resources. This
The separation of responsibilities makes different persistence managers work with different containers. It also makes the entity
BEAN has more portability between different EJB vendors and between various persistent managers.
If you use or learn THOUGHT Inc., you can generate BMP for EJB 1.1 containers (
Bean Management Persistentive) Bean's product Cocobase, how do you work on persistence managers?
It is already more familiar. Cocobase is available from object-to-relations reports based on Bean deployers
Interest, generate all database access logic for BMP Beans. In EJB 2.0, the persistence manager can
According to the deployment descriptor, the information provided by the abstract persistence option and the deployer completed the information provided by the work.
Map of CMP entity to the relational database. 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, it must define the combination between the bean and the persistence manager.
approximately. This contract exhibits in a new abstract persistence program. This program is a set of deployment descriptors
A set of code idioms in the new XML element and CMP entity beans are defined. In EJB 2.0, CMP
The bean class is declared as an abstract class, its persistence field and relationship field is the use of abstract read methods and writing
The method is visited, and the method of these two methods is mapped to the specific element in the XML deployment descriptor.
When deploying this bean, you will use a persistent manager tool to deploy a descriptor and bean according to XML
Class, to specifically implement this abstract bean class and its dependent object class. Specific implementation will include data access code,
This code will actually read and write into the database at runtime. In runtime, the container is used
The subclass generated by the persistence manager tool does not use the 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 here, which specifically illustrates abstract lasting
How to work in a sex solution.
An example CMP entity in EJB 2.0
In EJB 2.0, the accumulated entity bean managed by the container is defined as abstract, and its persistence fields are
Not directly defined in the bean class. As an alternative, an abstract persistence program has been developed, allowing
The BEAN provider indirectly states the persistence field and bean relationship. Below is one of the Employee Bean
Example, it uses a new abstract persistence solution. Please note that no persistence word is not declared in this bean class.
segment.
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, PUBLIC ABSTRACT VOID
SetContactInfo (ContactInfo Info);
Public Abstract ContactInfo
GetContactinfo ();
...
}
In this bean's XML deployment descriptor, the abstract persistence solution declares all fields and
Various relationships.
...
...
...
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>
XML elements used to describe the relationship of container management may become very complicated because they have to deal with various
The correspondence and direction of the relationship (one-way or two-way). The above code segment description, in order to describe
The simplicity of Bean and its dependent object class do you need. Although even simple relationships
It will also be converted to lengthy XML, but all of these elements are required so that the persistence manager can
Complex object maps are mapped to the database.
Although the XML element of an abstract persistence scheme for defining a CMP bean is CMP in EJB 2.0
The main problem, but for the sake of simplicity, this article no longer provides an XML example. Instead, this article will be purely
Abstract idioms must be used in the bean class to illustrate the basic concepts behind the CMP in EJB 2.0.
These code idioms are used with relationship elements in the XML deployment descriptor, and is defined by the latter, so you
There is no one without one, but they are easier to understand than the XML part of the program.
In addition to XML elements, abstract persistence programs also define a set of idioms, which are declared bean class
And it is inevitable when it is related to it. The method used to access and modify the field is strictly defined, the requirements
Use the set
Entity Bean classes and slave classes follow the same abstract persistence solution. Here's how to put ContactInfo
Objects are defined as an example of a dependent object class.
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, which is aborted with the physical bean, which is understood from it.
The key to the relationship between objects and entity beans. The dependent object is included in a specific entity, so delete
This entity will cause the slave object to be deleted. In terms of terms of the relational database, sometimes this is called cascading
delete.
Dependent objects, such as ContactInfo, in the relational field. Objective objects with physical beans form relations
Technically referred to as a slave object class. EJB client applications never directly access the dependent object class; this
Classs cannot be used as parameters or return values in the remote or local interface of the bean. Dependent object class is only to the bean class
It is visible.
The dependent object class is not suitable as a remote parameter type because they have the persistence logic at runtime.
close relationship. Persistent Manager extends an abstract slave object class to provide an implementation, available
Manage the persistence status of Beans at runtime. In addition, abstract persistence plans are also modeling data
- Instead of modeling for business concepts represented by enterprise-level beans - so as a design policy
Slightly, it makes sense to hide the EJB client to the EJB client.
For example, in addition to the simple address information required by the ContactInfo relationship field,
Contains many other information. Although you can use the subordinate objects in the abstract persistence scheme
ContactInfo (it is hidden on the client client), however, you have to use other objects to put this
Some data is actually exposed to the client. Below is an example, explaining how to hide the EJB client
ContactInfo slave object. In this case, address information is developed by examples of EJB 1.1
The Address object is exposed.
// 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 it directly from the remote interface.
Persistent field management of the device. Please note that the container management of firstname and lastname is used.
The persistence field is used in a remote interface.
A bean may have a variety of different relationships with various slave object classes, which are paired by this relationship
Definitions in terms of sex and direction. BEANs can have a pair and one-to-one relationship between the slave object class. E.g
Employee Bean may have only one benefit slave object class, but there may be many
ContactInfo slave object class.
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 ();
...
}
One-to-many relationship with the slave object class can be represented as a java.util.collection type, or
Ava.util.set Type (Note: Java.util.map and Java in subsequent versions of this specification.
Util.List is considered an additional return type), and the one-on-one relationship with the slave object uses the slave object
type.
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 Bean may have many sub-stage beans, and only one paired
BEAN. The following code segment uses the abstract persistence scheme in idiom, 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 java.util.collection type or 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-pair of other slave objects in the same bean.
Many relationships. In addition, the dependent object is also one of the other entity beans (except for his parent bean).
To one, a couple of relationships. The following example shows that the Benefit slave object class and the Salary dependent object
(How to have a one-on-one relationship between the compensation calculation procedure, and how to be with Investment Bean
There is 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.
Containers will manage persistence instances at runtime, thereby providing a robust environment with automatic access
Control and transaction control.
BEAN can also define the value of the slave object, which can be serialized, such as the EJB 1.1 example.
ADDRESS object. These values become lasting by serialization, they do not form the relationship with beans
Series - They are strict vessel management persistent fields.
A contract has also been defined between the container and the persistence manager to make the persistent manager obtain a transaction.
Handle and access the database connection pool managed by the container. This contract is slightly loose, and it needs to make it in the future.
More stringent, but it is the basis for the permanent manager to transplant transplantation across EJB container. Containers and persistence management
The details between the contracts have exceeded the scope of this article.
In addition to the definition of durability by abstract durability, EJB 2.0 also provides a new query language.
It is used to explain how the persistence manager should implement various lookup methods in CMP.
EJB query language
EJB Query Language (EJB QL) specifies how the persistence manager should implement in the local interface
Finding method. EJB QL is based on SQL-92, which can be automatically compiled by the persistent manager.
The body bean has higher portability and is easier to deploy.
EJB QL and Finding Methods
The EJB QL statement is declared in the deployment descriptor of the entity bean. 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 a persistence manager.
How to perform a lookup method. Each entity bean must have a FindByPrimaryKey () method. for
The query required to perform this method is very obvious - using the main key (one or more) fields in data
Find beans in the library, so you don't need any EJB QL statements.
The FindByzipCode () method is used to get all Employee Beans with a postal code. This will make this
Expressed in the following EJB QL in the deployment descriptor.
From contactinfo where contactinfo.zip =? 1
This statement is essentially all EMPLOYEEEEEEEe Beans that selects its postal code equal to ZIPCode parameters.
".
In the EJB QL statement used to find the method, you don't need to use the SELECT clause to indicate the content you want to select.
. This is because the lookup method will always select the same remote reference as its own bean type. In this kind of
In 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, there are navigable
Active relationship, then these lookup methods can even span from other beans abstract persistent programs
go with. For example, the FindbyInvestment () method will ask the lookup query to navigate from Employee to investment
Bean's abstract durability solution. Declare to express this EJB QL statement for this lookup operation as shown below
.
From element in benefit.investments where element.name
=? 1
The above statement is to say: "Select all such Employee Beans: its profit slate object contains at least one
Investment Bean reference, and its name is equal to FindbyNVestment () method
InvestmentName parameter. "
EJB QL and selection method
EJB QL is also used in a new query method called an EJBSELECT method, which is similar to finding method
, Just it is for use only. 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 distance of Bean itself.
Interface Type.
There are two options: EJBSELECT
The EJBSELECT
Bean instance. EJBSELECT
These selection methods are declared in the bean class as an abstract method and are used in these class business methods. under
The surface is an example of EJBSELECT
Explains how you can use them in your business method.
Public Abstract Class Employeebean IMPLEMENTS
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.
EJBSELECTINVESTMENTSINENTITY () 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 range of EJBSELECT
All venture capital in all employees in the whole company.
EJBSELECT
As in the query), the dependent object or any other Java type. On the other hand, the global selection method cannot be returned
Back to the slave object type.
The EJB QL statement for the selection method requires the use of SELECT clauses because they can return a broader range.
Value.
New EJBHOME method
In EJB 2.0, entity beans can declare some EJBHOME methods to perform with EJB components.
Related operations, but is not dedicated to a bean instance. EJBHOME method defined in the bean class
There must be a local method that matches therefrom in the local interface. The following code illustrates a local method
It is defined as the local interface of the Employee Bean. Applycola () method is used according to the most
Growth of COLA (Domestic Fee Adjustment) to update the salary of all employees.
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 (). EjbhomeApplyCola () method is not dedicated to a bean instance, it
The range is global, 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 salary =
Emp.Getannualsalary ();
SALARY = Salary (Salary * Increase);
Emp.Setannualsalary (SALARY);
}
}
}
BEAN's developers need to implement EJBHome methods for BMP and CMP entity beans. CMP implementation
It is possible to depends to a large extent on global selection statement (as described above) and the Finder party.
Law, and EJBHOME's BMP implementation will use direct database access and bean's Finder method.
To query the data and make changes.
MessageDriveNbean
In EJB 2.0, a basic change to the specification has added a new enterprise bean type.
MSSAGEDRIVENBEAN. MessageDriveNbean specializes in handling JMS messages in the network
. For many developers, JMS is a new example, so this article will spend some time step by step.
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
: Here, JDBC can be used to access many different relational databases
API, while JMS provides access methods that are also unrelated to vendors to access messaging services. Many manufacturers
JMS is currently supported, including IBM's MQSeries, BEA WebLogic JMS Service and
Progress's SonicMQ, this is just a few examples.
JMS enables you to pass messaging services (sometimes called message intermediary programs or routers) from one JMS
The client sends a message to another JML client. The message is a type object in JMS, from two parts
Composition: header and message main body. The header consists of routing information and metadata on the message. Message main body
Then carry the data or payload of the application. Divided according to the type of payload, you can divide the message
For several types, they carry: textMessage, sequential objects
(ObjectMessage), attribute set (MapMessage), bytestage, original value stream
"StreamMessage, there is also 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. ratio
It is understood that this is completely different from RPC-based (remote processes) systems such as EJB 1.1, CORBA
Recommended with Java RMI. In the RPC, the client calls one of the distributed objects on the server.
Method. The client is blocked before the method call returns; the client can perform the next instruction
Previously, wait for the method to end. In JMS, the client sends a message to a virtual channel (
Theme or queue), while other JMS clients book or listen to this virtual channel. When JMS client issued
When you send a message, it doesn't wait for a response. It performs a sending operation and then proceeds to execute the next instruction. Message
Can eventually forward to a plurality of clients, these clients do not need to respond.
JMS in EJB 2.0
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 the virtual name called the subject or queue.
aisle. On the other hand, MessageDriveNbean is the user or recipient of the message. It monitors specific
Virtual channel (topic or queue) and process messages sent to this channel. In order to better understand the message
The role of the message user, use sessionBean Bean to send a message using JMS,
Use a new MessageDriveNbean to use this same message.
JMS as an EJB 2.0 resource
Both session beans and entity beans are RPC-based components, in order to assemble various transaction components to
Together, this is a superior architecture. However, in some cases, the synchronous nature of the RPC will become one
Obstacles, this is why the access to JMS API is included in EJB 1.1 as a resource included.
Using the context named by JNDI environment, Bean can get a JMS factory and will be an asynchronous message.
Send 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 details to the message
The theme.
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.createtopicSession (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
The program is not important for handling orders, but they will be affected by a notification that has been processed by a order
beneficial. Such an example includes automatically adjusting the inventory system, and can add customers to the product catalog message
Single sales app.
Use JMS to enable the bean to publish (send) messages without blocking. Bean doesn't know who will receive
Go to the 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
Dynamically add or delete applications in a virtual channel, resulting in a more flexible system.
Applications that book the order topic will receive notifications for new orders, the application can use them to think
This notice is handled in any way. Book a variety of themes or connected from each queue
Applications that receive messages can be Java applications, EAI systems (for integrated legacy systems and ERP)
System) or MessageDriveNbean components, in JMS terms, they are all considered to be JMS
Client computer.
JMS and MessageDriveNbean
Although most JMS vendors provide a message intermediary tool to route messages from the sender to the recipient, but
Building a JMS client using (receiving) messages is the responsibility of application developers. In many cases
Next, the application that receives the message must strengthen, safe, and quickly retractable; it needs the infrastructure base
This is the same as the EJB application.
Due to this need, EJB 2.0 now includes the MessageDriveNbean type, which can make
Use JMS messages and handle these messages in the same strong, component-based infrastructure, so
In addition to providing the container infrastructure, EJB has another important advantage: concurrency processing. In EJB
In, a deployed message bean represents a single message user, but this bean itself is
Many bean instances provide services. Each bean instance can receive a message bean separately
Message. This means that the message bean does not have to use a message as a regular JMS client. Dispense
Solid beans can use the received multiple messages in concurrently, which can reach the traditional JMS application
Highly multi-throughput and much more scalability.
In order to illustrate the role of the message bean, it has developed a MarketingBean class, and it is from the order topic
Deploy the message to the usage. MarketingBean will extract ORDERDETAIL objects from the message.
And use it to add customers 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 message beans are not RPC components. It does not have a business method for EJB client calls. news
Bean listens to virtual message channel (topic or queue) and send it to the channel using other JMS clients.
news.
Each message bean constitutes a bean class, this class implements the MessageDriveNbean interface and one
XML deployment descriptor. Below is the definition of the MessageDriveNbean interface, all messages beans must
This interface must be implemented.
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 be
The router forwards 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 it from a pool.
A instance of the bean handles this message. When the BEAN instance calls its onMessage () method,
It will receive this message and can handle this message in any way it thinks is appropriate. Once
If the message is used, this message will not be transmitted to this message as long as the transaction is not aborted.
Any other instance of Bean.
Message Bean is similar to a stateful session bean, which is between two beans between two requests.
Do not hold any status. Therefore, the message-driven bean is stateless, but it is like a stateless meeting.
Like Bean, they can also have instance variables, which in this bean instance's entire survival
Increase in an average.
The last description of the message bean is that it is important to understand such a fact, that is, bean uses
The message is not necessarily generated by other beans. Message Bean can use manufacturers in accordance with JMS
Any subject or queue provided in any topic. Message Bean's message can be from other beans
BEAN, entity bean or message bean, non-EJB Java application, or even
Java's application (if its supplier meets JMS). For example, legacy applications may use
IBM's MQSeries sends messages to queues, and the message can be used by other legacy applications, and can also be used by message beans.
in conclusion
Compared to previous specifications, Enterprise JavaBeans 2.0 made some considerable changes. new
The CMP model is much flexible than the previous model, which allows various entities to establish models for complex object maps.
The same also provides a larger portability of the container. People are eager to look forward to defining a lookup and selection operation
Generic query language, which will also help improve portability.
This new MessageDriveNbean type will help make this powerful news to receive examples
The focus of focus is like EJB. Messages are extremely important in distributed hybrid calculations.
Components, including it in EJB is a proof of its importance.