J2EE Component Development: Entity EJB (below)

xiaoxiao2021-03-06  117

Outline: ===================================1, the client interface 1.1 Remote interface 1.2 Home interface, Example 2.1 BMP entity bean

2.1.1 EJBCREATE () Method 2.1.2 EJBPOSTCREATE () Method 2.1.3 EJBREMOVE () Method 2.1.4 EJBLOAD () and EJBStore () Method 2.1.5 Finder Method 2.1.6 Business Method 2.1.7 Database Call 2.2 Home Interface 2.3 Remote Interface 2.4 Deployment Descriptor 2.5 Client 2.6 Deployment and Run =================================== Text: ===================================

First, the client interface

In "J2EE Component Development: Entity EJB (on)", we understand the characteristics, use of entity EJB, use, and two persistent types. Compared with the session bean, the construction and use of the two HOME, Remote client interfaces are similar. In fact, in addition to adding a lookup device method in addition to the real BEAN's Home Interface Definition, there is only a subtle difference in semantics. Let's take a look at how to construct these interfaces of entity beans, and how the client accesses these interfaces.

1.1 Remote interface

The real BEAN's remote interface encapsulates the entity bean as seen by the client, the same as the construction method of the session bean Remote interface. The entity bean interface typically includes some GET methods and SET methods, which are used to extract and set data, respectively; at the same time, the Remote interface can also contain an interface definition of any application layer. Let's take a look at how to construct and use the Remote interface of the entity bean. Figure 1 shows the basic architecture involved in the constructing remote EJB interface.

Remote interfaces of all distributed EJB components, such as MYENTITITYEJB shown in Figure 1, must expand the Javax.ejb.ejbObject interface. Like a session bean, entity beans utilize the underlying Stub program, the Skeleton program, and the management service provided by the container to implement distributed and manageable access from the client interface to the server-side EJB component. In fact, in terms of entity beans and session beans, the true difference between the two Remote interfaces is only in some semantic subtle differences. Like the session bean, each entity bean component has a remote EJB interface. This interface provides a distributed interface for entity beans, allowing client programs to call entity beans's application layer logic. For distributed application layer methods on each entity bean component, such as myentityejbean.somethod (), EJB client remote interface must define a corresponding application layer method, such as myentityejb.somethod (). An attached impact brought by distributed characteristics is that each method in the application layer can declare it to throw java.rmi.RemoteException. Of course, this rule is only valid for the method of providing a distributed service on the server-side component. In addition to the application layer method on the EJB remote interface, there is a set of methods from EJBObject inheritance on the remote entity bean object to be used. 1.2 home interface

The entity bean is created, looking for, or dismantled entity beans through the home interface. In fact, creating entity beans have caused a new data unit into the data source (for example, inserting a new row into the database table). The interface used to find the entity bean provides a mechanism for finding the data unit, and the result returned the result complies with object-oriented style (entity bean object). Remove an entity bean leads to the corresponding data unit from the database. In this section, we will learn how to create and utilize entity Bean HOME interfaces, how to perform these basic operations and other other auxiliary operations. Figure 2 shows how the basic architecture involved in the constructive entity Bean Home interface and how the client uses these interfaces. To get an application layer EJB Home interface object, such as the named INTYHOME (it must derive from the standard javax.ejb.ejbHome interface), we only need to use JNDI to find the named HOME reference. The client STUB program of the entity bean implements the application layer HOME interface of the entity bean instance, where the server, the Skeleton program, and the container are responsible for mapping calls from the Stub program.

The client's way to find the entity Bean Home object is the same as the lookup session bean home object. Regardless of the customer program runs within the J2EE container, JNDI is used as a separate program outside the container. If the client runs within the J2EE container, you can use

Elements reference EJB HOME interface. If the entity bean is a client program, you can be in the ejb-jar.xml file.

Definition within the element

element.

One or more Create (...) methods are defined on the home interface of the entity bean, which represent various ways of creating the data units corresponding to entity beans. For each EJBCREATE (...) method in the entity bean class, a CREATE (...) method must be defined in the Home interface. The Create (...) method can contain zero or more input parameters, match the initialization parameter type required by the corresponding ejbcreate (...) method, but these create (...) methods returns an entity bean remote interface Examples (such as MyentityEJB). In addition, the Create (...) method must also be able to throw java.rmi.RemoteException and javax.ejb.createException exception.

The Create () method is not the only application layer method that can be defined on the entity bean home interface. The HOME interface can also define a set of FINDXXXXX (...) methods, and the client is queried in the entity bean by this group. For each ejbfindxxx (...) method defined by the entity bean class, there must be a corresponding FINDXXX (...) method on the entity bean home interface. For the CMP entity bean, the legal FINDXXX (...) can be determined from the entity bean deployment descriptor due to the Explicit-defined EJBFINDXXXX (...) method in the Bean class. Each FindxxxX (...) method defined on the entity bean home interface should also declare that RemoteException exceptions can be thrown to the client program and the FINDEREXCEPTION exception.

Entity Beans must define an ejbfindbyprimarykey () method, so the Home interface must at least define a FindByPrimaryKey () method. FindByPrimaryKey () must return a handle of an entity bean remote object (such as myentityejb). The container is responsible for associating the primary key returned by the entity bean method EJBFINDBYPRIMARYKEY () to the specific bean instance and the returned entity bean client remote interface Stub program. The definition of other Findxxx (...) methods must also match the corresponding EJBFINDXXX (...) method, both must have the same input and output parameters. The difference between the client is that the Enumeration or Collection object returned from the FINDXXXX (...) method contains the implementation of the entity bean remote object; on the server-side entity bean component, the corresponding EJBFINDXXX (...) method returned to the collection included It is the primary key.

Second, instance

This example is a bean management persistent entity bean, which is a simple bean that describes the salary level information. The status information of the entity bean saves the PayTable table in the relational database. The structure of the PayTable table is as follows:

Create Table PayTable (Empname Varchar (10), PayRate Real;

Where EmpName represents the employee name, PayRate indicates the salary level. EmpName is the primary key. The entity bean class, the HOME interface and the Remote interface are implemented in Payejb.java, PayHome.java, and Pay.java. The client is PayClient.java.

2.1 BMP entity bean

Payejb entity Bean class meets the following requirements:

Implement the EntityBean interface. The bean class is defined as public. The bean class cannot be defined as abstract or ultimate. Implement zero or multiple EJBCREATE () methods and EJBPOSTCREATE () methods. Implement the EJBFINDXXXX (...) method. Implement business methods. Finalize () methods cannot be implemented.

2.1.1 ejbcreate () method

As mentioned earlier, when the client calls the create () method, the EJB container calls the corresponding ejbcreate () method. Payejb has only one ejbcreate () method, which completed the following tasks:

Insert the status information of the entity bean into the paytable table. Initialize the instance variable. Return to the primary key.

code show as below:

public String ejbCreate (String empName, float payRate) throws CreateException {if (empName == null) {throw new CreateException ( "employee name is required.");} try {String sqlStmt = "INSERT INTO PayTable VALUES (,?? ) "; Con = ds.getConnection (); preparedStatement Stmt = con?preparestatement (SQLSTMT); Stmt.setString (1, Empname); Stmt.Setfloat (2, paydate); stmt.close ()"; stmt.close () } Catch (SQLEXCEPTION SQLE) {throw new ejbexception (SQLE);} finally {{i (con! = Null) {con.close ();}} catch (sqlexception sqle) {}} this.empname = Empname THISPAYRATE = PayRate; Return Empname;

Access control modifiers must be public. The return value type must be the primary key (only for the persistence of bean management). The parameter value must be a legal Java RMI type. The method does not have a Final or Static modifier.

It is worth noting that non-J2EE applications can also be inserted directly into the database. For example, you can use the SQL command to plug the record into the paytable table. Although the entity bean corresponding to the record is not created by the ejbcreate () method, the client program can find this entity bean.

2.1.2 ejbpostcreate () method

After the EJB container completes the call to the EJBCREATE () method, the ejbpostcreate () method is called immediately. Unlike the ejbcreate () method, the EJBPostCreate () method can call the enttemysKey () and getPrimaryKey () methods defined by the EntityContext interface. The ejbpostcreate () method can usually be empty, such as Payejb's ejbpostcreate () is empty. The ejbpostcreate () method must meet the following requirements:

The quantity and type of parameters must match the corresponding EJBCREATE () method. Access control modifiers must be public. There is no Final and Static method modifiers. The return value type must be Void.

2.1.3 ejbremove () method

The client program removes the entity bean by calling the remove () method, which causes the EJB container to call the EJBREMOVE () method, and the EJBRemove () method removes the status information of the entity bean from the database. Payejb's EJBREMOVE () method is as follows:

public void ejbRemove () {try {String sqlStmt = "DELETE FROM PayTable WHERE empName =?"; con = ds.getConnection (); PreparedStatement stmt = con.prepareStatement (sqlStmt); stmt.setString (1, empName); stmt. EXECUTEUPDATE (); stmt.close ();} catch (sqlexception SQLE) {throw new ejbexception (SQLE);} finally {type {if (con! = null) {conif.close ();}} catch (SQLEXCEPTION SQLE) {}}} 2.1.4 EjbLoad () and EJBSTORE ()

In the Payejb class, the EJBLOAD () method first constructs a sql select command, then execute the SQL command to read the salary level information from the database, save it to the instance variable. The EJBStore () method first constructs a SQL Update command and then executes the Update command to update the data in the database. See the implementation code in Payejb.java.

2.1.5 Finding Method

Payejb defines two finder methods:

Public String EjbfindByPrimaryKey (String PrimaryKey) Public Collection EJBFINDINRANGE (FLOAT LOWERLIMIT, FLOAT UPERLIMIT)

The first method is found according to the primary key, returns the eligible employee; the second method is found according to the specified salary rating range, returns a collection of eligible employees. The implementation code for the second method is given below:

public Collection ejbFindInRange (float lowerLimit, float upperLimit) throws FinderException {try {String sqlStmt = "SELECT empName from PayTable" "WHERE payRate BETWEEN AND??"; con = ds.getConnection (); PreparedStatement stmt = con.prepareStatement (sqlStmt ); Stmt.setfloat (1, lowerlimit); stmt.setfloat (2, upperlimit); resultset = stmt.executeQuery (); arraylist list = new arraylist (); while (rs.next ()) {string id = r = rs .get.close ();} stmt.close (); return new ejbexception (sqle);} finally {try {if (con! = null) { Conit ();}} catch (sqlexception sqle) {}}} For BMP entity beans, the Finder method must meet the following requirements:

EJBFindByPrimaryKey () method must be implemented. The name of the method must be prefixed with EJBFIND. Access control modifiers must be public. The modifier of the method cannot be Final or Static. The parameter and return value type must be a legal Java RMI type. The return value type must be a collection of primary or primary keys.

2.1.6 Business Method

PayeJB defines two simple business methods, setPayrate, and getPayrate (), which are used to set up and get salary.

2.1.7 Database Call

The following table summarizes the database access type of each method in PayeJB:

Method, corresponding SQL call EjbcreateInsertejbfindByprimaryKeyselectrtejbfindInrangeseelectejbloadselectejbremoveDeleteejbstoreUpdate

In PayeJB, the business method ultimately completes the database calls through the EJBLOAD () method and the EJBStore () method, so the table does not show the database call type corresponding to the business method.

2.2 HOME interface

The client creates and finds the entity bean via the HOME interface. The PayHome interface is defined as follows:

import java.util.Collection; import java.rmi.RemoteException; import javax.ejb *;. public interface PayHome extends EJBHome {public Pay create (String empName, float payRate) throws RemoteException, CreateException; public Pay findByPrimaryKey (String primaryKey) throws FINDEREXCEPTION, RemoteException; Public Collection Findinrange (Float LowerLimit, Float Upperlimit) throws FingeRexception, RemoteException;} 2.3 Remote Interface

The Remote interface extension javax.ejb.ejbobject defines a business method that can be called by the client. Payejb's Remote interface is defined as follows:

import javax.ejb.EJBObject; import java.rmi.RemoteException; public interface Pay extends EJBObject {public void setPayRate (float payRate) throws RemoteException; public float getPayRate () throws RemoteException;}

Each method in the Remote Interface must match one of the methods in the EJB class, the parameters of the method, and the return value type must be a legal RMI type. In addition, the THROWS of the method must contain java.rmi.RemoteException.

2.4 Deployment Description

Before deploying EJB, you should first package the EJB into a JAR file. Each EJB module (JAR file containing EJB components) must contain an EJB-JAR.XML deployment descriptor. Although usually we can use the GUI interface tool, write the EJB-JAR.XML deployment descriptor by filling out, but understanding EJB-JAR.XML is still necessary. See the example in this article download code.

2.5 client program

The client PAYCLIENT.JAVA first inserts four records into the paytable table, then look for the record of the employee name "Sun Wukong", and outputs its salary level. Next, the client program modifies the employee's salary level. Finally, the customer program finds the employee of the salary of 5.0 to 20.0, and the output list. Below is the operational results of PayClient.java.

2.6 Deployment and operation

Let's take a look at how to run this app on the Sun J2EE SDK and Cloudscape database. The Cloudscape database can be downloaded with J2EE SDK. First execute the J2EE command to start the J2EE server. Then start the Cloudscape database server from the command line:

Cloudscape -start

In another command window, execute Cloudscape -ISQL to enter the Cloudscape console, perform the SQL CREATE command given in the previous, create a PayTable table. In the next description, we assume that the application has been encapsulated into an EAR file PayApp.ear. For a detailed description of the J2EE application package and deployment, see the relevant documentation of the development platform. Start J2EE SDK deploytool, select the menu "File-> Open", open the Payapp.ear file. Next, select the menu "Tools -> Deploy" deployment application. When a deployment prompt occurs, select the Return Client Jar check box. In a command window, enter the directory where the EAR file (PAYAppClient.jar file) is located, set the environment variable AppcPath to PayAppClient.jar. Then, perform the following command: runclient -client payapp.ear -name payappclient -textauth

In the login prompt, enter the username J2EE and enter the password J2EE. See Figure 3 for the output of the client program. Download this article:

J2EEENTITYEJB2_CODE.ZIP

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

New Post(0)