J2EE Component Development: Entity EJB

xiaoxiao2021-03-06  118

Outline: ====================== 1, outline 1.1 persistence 1.2 Shared Access 1.3 Primary key 1.4 relationship 2, entity bean and JDBC three, entity EJB component 3.1 bean Management persistence 3.2 Persistence of container management ======================== Text: ============== ========== 1, the outline entity bean represents an entity in a persistent data storage system (usually database). Compared with message-driven beans, session beans, entity beans are characterized by persistent, shared access, ownership, and main keys, and relationships.

1.1 persistence

The status information of the entity bean is saved in a persistent storage system such as the database, so it has a persistent feature. This means that even in addition to the living cycle of the application or J2EE server process, the status information of the entity bean is still valid. Entity Bean's persistence divided into two types: bean management persistence (BMP), or container management persistence (Container-Managed Persistent, CMP). The type of persistence can be declared in the EJB deployment descriptor. For the persistence of bean management, developers should write the code to access the database. For example, ejbcreate () executes a SQL insert command, developers must construct and execute SQL INSERT commands and other related calls. For the persistence of container management, the container automatically completes the necessary database calls. For example, when a client requests an entity bean, the container generates a SQL INSERT command. The code written by the developer does not contain any SQL calls. The container is also able to automatically synchronize the status information of the entity bean and the data saved in the database, which are often referred to as "container-managed field). The field of container management is also declared in the deployment descriptor. The persistence of container management has two significant advantages: First, the container management persistent entity bean code amount is less; second, since the bean does not contain any database calls, it has the characteristics of a neutralized database type. Of course, these advantages sometimes become limitations, in some cases that require high flexibility, Bean management persistence will be the preferred solution. For example, when the container does not support the CMP entity bean, or the developer wants to have more control over the data processing, or when a data source is too complex, it is difficult to implement an efficient CMP entity bean mapping, we should use BMP entity Bean.

1.2 Sharing Access

Entity Beans can be shared by multiple client programs. Since multiple client programs may modify the same data, it is important to provide transaction support for entity beans. Generally, the transaction management mechanism is provided by the EJB container, and the developer does not need to set the boundaries of the transaction in the bean. Transaction attributes can be specified in the Deployment Descriptor of the Bean.

1.3 primary key

Each entity bean has a unique object identifier. For example, a Customer entity bean can be identified by customer number. The unique identifier of the entity bean is also called a primary key, which enables the client to locate a specific entity bean instance. When the EJB client creates or looking for a specific database record through the interface of the entity bean, the container associates a primary key to the EJB entity bean handle that returns to the client. For example, if the customer's name is the primary key, for the container, this name should uniquely identify a record of the Customer table in the database; from the perspective of the client, it maps to a unique Entity bean instance. 1.4 relationship

Just as the table in the relational database, relationships can also be established between entity Beans. The implementation of the relationship is different depending on the type of persistence. For the persistence of bean management, the relationship requires developers to write code implementations; for the persistence of container management, the relationship is implemented by the container. For this reason, the relationship is generally referred to as container-management relationship for container management. According to the characteristics of the entity bean, it is recommended to use the entity bean to include: When the bean focuses on describing the business entity instead of a business process. When the status information of the bean requires persistence.

Second, entity beans and JDBC

Connection and access databases are the basic requirements of most J2EE applications, and J2EE provides support with JDBC. Some vendors (such as Oracle) and the next version of the J2EE specification will support access to the database via SQLJ, but this article still introduces database access based on JDBC. The J2EE platform provides support for JDBC APIs, allowing us to configure JDBC resources via a deployment descriptor in the XML form, connect JDBC resources through JNDI. The configuration of the JDBC driver, the declaration of the data source is complete through the J2EE module deployment descriptor in the XML format. Both session beans and entity beans can define in the J2EE deployment descriptor

Elements, each EJB can configure zero or more JDBC resources.

For example, the following example shows how to configure JDBC resources for entity EJBs in an ejb-jar.xml file:

... ... JDBC / Cloudscape javax.sql .Datasource Container Shareable ...

After the above configuration, it is very simple to use data resources within the entity EJB, just find the named data source within EJB, then get a javax.sql.dataSource handle. You can get a java.sql.connection object with the DataSource object. How to assign the Connection object to the bean is determined by the container, but generally, the container sets a database connection pool. Next, Bean can use the Connection object to construct a JDBC database operation command as usual, and extract the result set. If the persistence of the entity bean is managed by bean, it must manage the database connection itself. Although this article only accesses JDBC resources through entity EJB, JDBC resources can also be accessed from session beans. If you want to access JDBC resources within a session bean, deploy the descriptor element in the EJB

Within the child element, pass one or more

Elements are configured.

Third, the entity EJB component

The entity bean is a constituent element that describes the Java class defined by the database data logic unit, the domain map defined by the entity bean class to the database mode definition. In the simplest case, the field of the entity bean is directly mapped to the list of database tables, and the entity bean itself is equivalent to a database of a database, and the relationship between the entity beans is similar to the relationship between the tables. The connection result of the table can also be regarded as entity beans, and the constituent elements of these data resources correspond to the domain of the entity bean class.

If the domain of the entity bean instance contains valid data, the instance corresponds to a specific data unit in the data source, or, an instance of an entity bean corresponds to a specific record in the table, or corresponds to a table connection query. result.

3.1 Persistence of Bean Management

Many concepts and techniques for constructing BMP entity beans are equally applicable to CMP entity beans. However, as we will see below, the BMP entity bean requires manually writing a lot of code. In some cases, writing BMP entity beans and writing JDBC-based components from scratch, the difference is only in the package of JDBC logic, in particular, the standard method on the BMP entity bean suggests which JDBC statements will be created and processed.

Figure 1 shows the basic architecture involved in constructing the BMP entity bean.

Common, non-final, non-abstract entity beans, such as MyBeanManageTryEJBean shown in Figure 1, must implement a javax.ejb.entityBean interface. The EntityBean interface extension is extended from the EnterpriseBean interface. The EntityBean interface defines actions that a set of entity beans must implement, which is necessary for the EJB container management bean's life cycle. Of course, Bean management persistent entity beans can also implement business methods, such as the SomeMethod () and AnotherMethod () methods shown in Figure 1. Generally, bean management persistent entity beans also define some status information in the form of domain variables, including buffer versions of database recording values ​​in these status information. The final point is that the entity bean must have a public, there is no parameter constructor, and the femalize () method should not be implemented. The javax.ejb.entityContext interface is implemented by the container, which provides a handle that points to the context of the entity bean. EntityContext extension from a more general EJBContext interface and defines a method of obtaining a remote EJB interface handle, and a method for obtaining the primary key of the bean instance. In a class that implements the EntityBean interface, the container will immediately call the setentityContext () method of the bean immediately. For your convenience, Beans should save this value in a domain. The entity bean should also implement the unsentityContext () method. When the entity bean disconnects the contact with the container context, the container will call the unsetentityContext () method. When the client wants to find instances of entity beans corresponding to the specific data unit, the container will call one of the EJBFINDXXXXX (...) methods on the entity bean (also known as the lookup method). EJBFINDXXXX (...) method-playing role is similar to the role of the SQL Select command in the database operation. When performing these methods, if an application layer error occurs, the BMP entity bean should generally throw a FINDEREXCEPTION exception. All entity beans must define an EJBFindByPrimaryKey () method. This method must use the primary key of the entity bean as a parameter, verify that the data unit identified by the primary key does exist in the database, and then returns the primary key to the container. If the specified data unit does not exist, the BMP entity bean should throw the ObjectNotFoundException exception. ObjectNotFoundException is an exception of the FINDEREXCETITION, indicating that the specified target cannot be found. Generally, BMP entity bean constructs a select command in the EJBFindByPrimaryKey () method, querying the database via the JDBC to verify that the data with the specified primary key does exist in the database. In addition to the EJBFindByPrimaryKey () method, the BMP entity bean can define multiple additional EJBFINDXXXX (...) methods, these methods with zero or more input parameters related to business, according to these parameters in the database Find the qualified data unit. For each set of data units, the EJBFINDXXXX (...) method must return a collection of primary keys corresponding to these data units. When implementing these methods, we can use the JDBC API to execute the SQL SELECT command, and then use the result set to construct a collection of related primary key objects. If the result set is not included in the result set, the return value should be an empty collection. Entity beans can define multiple ejbcreate () methods, or there is no EJBCREATE () method; these ejbcreate () methods can bring multiple parameters, or without parameters.

From the function, these optional ejbcreate () methods are similar to the INSERT command in the database operation: insert a data unit in the data source corresponding to the current entity bean type, fill in this data unit with various data obtained by the entity bean. The entity bean can obtain this data by constructing the initialization of domain variables during the construction of the bean instance, and all data that is incorporated as the EJBCREATE (...) method can also be used. The container calls the entity bean's EJBCREATE (...) method according to the request of the client program, and the object returned by the EJBCREATE () method represents the primary key of the newly created entity bean. The BMP entity bean must implement the necessary database connection logic so that the EJBCREATE () method performs the SQL INSERT command for the database. Basic tools to complete this task are JDBC APIs, we can configure it through the XML form. If you cannot create an entity bean for some reason, the BMP entity bean can throw the CreateException exception. If the entity bean cannot be created is due to the data unit having the same primary key, the BMP entity bean can throw the subclass of CreateException's subclavation. Exception. Corresponding to each EJBCREATE (...) method, the entity bean must define an ejbpostcreate () method with the same input parameters. When the container is called, and after the instance of the entity bean is associated with the client reference, it will call the ejbpostcreate () method. Therefore, all initialization operations that need to be performed after the EJBCREATE () method is performed, and can be completed within the ejbpostcreate () method. If the EJBPOSTCREATE (...) method is executed, an error occurred, it can also throw the CreateException exception. When the client requests to remove the entity bean instance, the container will call the EJBREMOVE () method. EJBREMOVE () method of the entity bean removes the currently associated data unit from the database, which is functionally similar to the delete command of SQL. BMP entity beans should use the GetPrimaryKey () method defined by EntityContext to get the hips of the primary key, and then construct the SQL DELETE command for the data unit. If an error occurs when trying to delete data, the EJBREMOVE () method can throw the RemoveException exception. Similar to state session beans, entity beans must also implement the EJBPassivate () method and EJBACTIVE () method. The container calls the EJBPassivate () method before returning the instance of the entity bean to the buffer pool. The operation of the ejbactivate () method is basically the reverse process of the ejbpassivate () operation, the container is called according to the request of the BEAN instance according to the client program, and the ejbactive () method is called when the previously passivated bean is transferred to the active state. The EJBPassivate () method and EJBACTIVE () method are used to turn off and open the resources of the non-data source, and the EJBLOAD () method and the EJBStore () method are used to process database data. When the container is synchronized with the status of the BEAN in the domain and saving the data in the database, it calls the EJBSTORE () method or the EJBLOAD () method. If the container needs to update the corresponding database record with the data update in the bean instance, it calls the EJBSTORE () method. Therefore, from functionally, the EJBStore () method is equivalent to executing the Update command of SQL. Generally, when the EJBSTORE () method is called, the BMP entity bean constructs and executes the SQL Update command through the JDBC. If the container needs to update the status of the entity bean in the database, it calls the ejbload () method.

That is, the EJBLOAD () operation is updated is an entity bean instance in the data unit in memory. Typically, the EJBLOAD () method first adjusts the GetPrimaryKey () method on the associated EntityContext, determines the data unit associated with the entity bean instance. Then, beans query the latest data of the data unit through the JDBC and update the state of the bean. 3.2 Persistence of container management

As mentioned earlier, constructing BMP entity bean is a more cumbersome thing. Compared to applications of access to the database directly by JDBC, the workload of writing BMP entity beans is not equal. However, EJB also provides a way to simplify entity beans, which is an entity bean for container management persistence (CMP). When using the CMP entity bean, the container implements all JDBC database access logic. That is, whether to transfer data from the entity bean object to a relational database or from a relational database to the entity bean object, the container that supports the CMP entity bean has an essential "object to the relationship" mapping. The following description is mainly for the development of CMP entity beans to develop BMP entity beans, no longer repeat that some concepts of CMP and BMP. Figure 2 shows the basic architecture involved in constructing the CMP entity bean. Common, non-final, non-abstract CMP entities, such as MYCONTAINERMANAGEDEJBEAN shown in Figure II, must implement an EntityBean interface. Of course, the container management persistence entity bean can also implement business methods, such as the SomeMethod () and AnotherMethod () methods shown in Figure II. It is also important to note that the CMP entity bean must have a public, non-parameter constructor, and should not implement a femalize () method.

It should be particularly note that the CMP must define all of the domains managed by the container into public and ensure that the relevant types are serializable. The domain managed by the container directly maps the elements of the data unit associated with the CMP entity bean, for example, the domain managed by the container can map directly to a list of database tables. The definition of the container through the EJB Deployment Descriptor knows which domains will be managed by the container. The primary key of the CMP entity bean can be specified as a domain of the bean, or you can define a separate class with one or more public domain names (these common domain names correspond to the domain name of the CMP entity bean), and then define this class Primary key. To set or cancel the EntityContext associated with the CMP entity bean, we use the setentityContext () method and unsetentityContext () method. As the BMP entity bean, the container is called these methods on the CMP entity bean, and the location of the time in the bean life cycle is also the same. The CMP entity bean no longer requires developers to manually write EJBFINDXXXX (...) methods. For the CMP entity bean, the container depls the relevant configuration information from the EJB deployment descriptor and then determines how to implement such a method. Therefore, for developers, the implementation of these methods is completely transparent. The specific implementation mechanism of these methods may be completed by the EJB Support Platform in the subclass of the CMP entity bean, or it is possible to complete the independent component of the resulting call and returns the result. However, regardless of the implementation mechanism of the underlying, the developers of the CMP entity bean don't have to pay attention to how to write code to support these EJBFINDXXXX (...). For the CMP entity bean, the EJBCREATE (...) method is also optional, and the bean developer does not need to write code in the database INSERT operation in order to support these methods. Developers are required to ensure that each of the parameter values ​​managed by the container is used in a suitable default or passing the parameter values ​​that are passed to the EJBCREATE (...) method correctly. The CMP entity bean must implement the EJBPostCreate (...) method that matches the ejbcreate (...) method. Before deleting the data associated with the CMP entity bean, the container is called before the data associated with the CMP entity bean. When writing an EJBREMOVE () method, developers only need to pay attention to the operations that must be performed from the database, actually delete data from the database is implemented by the container, and the container will throw appropriate EJB exception when necessary. The ejbpassivate () method and ejbactivate () method must be implemented by the CMP entity bean developer, which is the same as the BMP entity bean. When implementing an EJBPassivate () method, developers should clear all resources that are unrelated to the data source; accordingly, when implementing the EJBActivate () method, they should be re-obtained. For most of the original BMP entity beans implemented within EJBLOAD () and EJBSTORE () methods, the container of the CMP entity bean will also be automatically processed. In the BMP entity bean, the actual data store operation is implemented by the EJBStore () method, and now these operations are responsible for the container, and developers are only responsible for the domain to manage all container management, such as obtaining those container management. The latest value of the domain. Similarly, when implementing the EJBLOAD () method, the developer of the CMP entity bean is only responsible for "propagation" various modifications to the bean domain value. When the container completes the update of the domain value managed by the container, the container calls the EJBLOAD () method, and the EJBLOAD () method should reflect all the change results to other status data related to this. This article will provide an example of a BMP entity bean development. Here we first take a look at some of the points in the CMP entity bean development process.

First, the CMP entity bean class must be defined as public and abstract. At the same time, the CMP entity bean class must implement: EntityBean interface. Zero or multiple EJBCREATE () methods and EJBPOSTCREATE () methods. These methods must be defined as Abstract to persistent domain and relational domain definitions. Various Select methods, and these methods must be defined as Abstract. Business method. Container management persistence entity beans can have persistent domains and relational domains, which are virtual, so they are not directly written directly as instance variables to the class, but specified in the deployment descriptor. The container automatically performs database storage and extraction operations for the persistence domain of the CMP entity bean. To support access to these domains, the CMP entity bean must define an abstract accessor method. The name of the accessor method begins with GET or SET, followed by the persistent domain or the name of the relationship domain. For example, suppose the CMP EJB deployment descriptor specifies the Name and Salarit of two persistent domains, and the EJB must be defined as follows:

public abstract String getName (); public abstract void setName (String name); public abstract double getSalary (); public abstract void setSalary (double salary); another example, assume that a player can belong to multiple groups, can be associated with an instance PlayerEJB To multiple TeameJB instances. To describe this relationship, PlayeRejb defines a relational domain Teams in the deployment descriptor. In the PlayeRejb class, the accessor method of the Teams relational domain is defined as follows:

Public Abstract Collection GetTeams (); Public Abstract Void SetTeams (Collection Teams); CMP entity beans can also define the SELECT method. SELECT methods have some of the same features as the finder method:

SELECT method querying the database and returns the result of the query. The deployment descriptor specifies the EJB QL query for the SELECT method. The CMP entity bean class does not implement the SELECT method, but is implemented by the container. However, the SELECT method has a significant difference with the finder method. For example, the SELECT method is not exported in any local interface and remote interface, so it cannot be called by the client program, and can only be called by the method implemented by the entity bean. Typically, the SELECT method is called by a business method. The SELECT method must be declared in the following rules:

The name of the method must be prefixed in EJBSELECT. The access control modifier must be public. Methods must be defined as Abstract. The Throws clause must contain javax.ejb.findection. Below is an example of a statement of the SELECT method:

Public Abstract Collection EJBSelectSports (LocalPlayer Player) THROWS FINDEREXCEPTION; the following table compares the difference between the CMP entity bean and the BMP entity bean.

Project Container Management Persistence Bean Management Persistribution Class Definition Abstract Non-Abstract Database Model The Tool Generation By Developer Writing Persistence Status Information by Persistence Virtual Field Description As an instance variable Writing persistence domain and relationship domain The accessor method (GET method and SET method) must not be the FindByPrimaryKey method is responsible by the container by the developer 's custom-made Finder method is responsible by the container, but the developer must define the EJB QL query by the developer SELECT method is responsible for the container without EJBCREATE () The return value of the method NULL primary key, whether it is the type of persistence, the writing rules of the business method are the same. 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-125219.html

New Post(0)