J2EE Component Development: Entity EJB (on)

xiaoxiao2021-03-06  117

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;

As another example, it is assumed that one athlete can belong to multiple groups, then a PlayEReJB instance can be associated with 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);

The CMP entity bean 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. In "J2EE Component Development: Entity EJB (below), we will continue to understand the client EJB client interface (Home interface and remote interface) and understand the development process and precautions of entity EJB through instances.

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

New Post(0)