J2EE development practices based on JBoss in the Win2K environment ---- 之: CMP entity bean writing and deployment

zhaozj2021-02-16  53

J2EE development practices based on JBoss in the Win2K environment ---- 之: CMP entity bean writing and deployment 1. Introduction In the previous section of a series of articles, we give the method of writing BMP and detailed The difference and commonality of BMP and CMP. BMP and CMP are the entity bean (Entity Bean) defined in the EJB2.x specification, one entity bean consists of multiple classes and interfaces, we can think that an entity bean represents a table in the database (just think so), an entity A specific object of Bean represents a record in this table. That is, the entity bean is a data middleware located between the database and the user application. About why it is necessary to engage in this middleware, I have given a sufficient reason to explain in the previous section. This data middleware is managed by the EJB container. Specifically, when the entity bean is deployed, the EJB container fills the data in the data table to the entity bean through the EJBLOAD () method; when the entity bean object is When released, the EJB container stores the data in the entity bean to the data table in the EJBStore () method of the entity bean; can keep the database table with the entity bean data middleware synchronization through the above two steps. First, the above synchronization method is described in BMP, which is described in our own, and in our CMP, these synchronization methods are automatically implemented by CMP. Second, the CMP entity bean does not contain a field that shows the declaration, as we show a few fields in the BEAN file in the last section of the declaration in the CMP. But how do they correspond to the database table? Things are this, although there is no display declaration, we can imagine them or actually exist (it declares in the deployment descriptor file), we set their values ​​through a series of getter / setter methods. In BMP, we write a getter / setter method. In CMP, we only need to declare these getter / setter methods as the Abstract type, and the EJB container is automatically generated according to our deployment descriptor, so we are It can be called in our CMP bean. At the same time, the implementation of the query method and the query method in the CMP is also different. In BMP, we look for all the query entity beans in the HOME interface, all of which we will implement them. However, in CMP, these lookup methods can also be omitted when writing beans, and then we define these findings in a deployment description file (which is similar to simple SQL query language). Below, I will specify the specific programming, and the two are different and how to write and deploy CMP in JBoss. Second, the method steps of writing and deploying CMP and its differences in BMP, writing deployment BMP and CMP have the following and several different places: 1. All need to first define the entity bean corresponding to the data in the database. Table 2, all need to configure the database connection pool support file, specifically, see the two ------- Database connection pool configuration and test. This step makes the EJB container can be connected to the database via a connection pool. 3. Write the Remote interface, this CMP and BMP are the same as a statement, such as business logic methods, to write some methods that expose to remote calls, such as business logic. 4. Write home interface, this CMP and BMP are the same, all define a query method on some HOME interface. Note that each entity bean requires at least a FindByPrimaryKey (PK) method.

Just, the lookup method defined here is implemented by the bean class in BMP. In CMP, they are not implemented by the bean class, which is implemented by the deployment descriptor file with the EJB-QL declaration and implemented by the EJB container. 5. Write the primary key class, which is the same. 6, write the bean class, this is the biggest difference between BMP and CMP. In BMP, we need to clearly implement the getter / setter method, you need to clearly implement the EJBLOAD () / EJBStore () method and various lookup methods, and connection database Method; in our CMP, these methods we only need to make a simple statement, it is possible to realize an empty method, and the lookup method does not have to declare. At the same time, we need to declare the getter / setter method as the Abstract type, which is implemented by the EJB container, we can call it in the bean method. (Program of the Example of Released) 7, write EJB-JAR.XML files, which is the EJB 2.0 specification standard defined, which defines the various information of our entity bean. This BMP and CMP are the same, however, in the EJB-JAR.XML file of the CMP, in addition to the various properties of the bean, such as Name, Remote, HOME interface, etc., it is necessary to define getter / setter in the entity bean. The corresponding declaration field information, EJB container maintenance corresponds to the corresponding relationship between entity beans and database table fields according to the fields of these declarations; at the same time, we need to describe the EJB-QL language in the ejb.jar.xml file of CMP. We are defined in the HOME interface. That is, the descriptor file EJB-JAR.XML of CMP is more than BMP's EJB-JAR.XMLL: First, the declaration of the field maintained by the EJB container; second, use the EJB-QL method to declare the HOME interface Find a method. Here, the EJB-QL method is similar to SQL syntax, which includes basic SELECT, FROM, WHERE et al., Can be viewed for EJB-QL reference. 8, write jboss-service.xml files, this file declares that the entity bean's JNDI information, through its content, we can find the bean through the lookup ("JNDI-NAME" in the program that calls EJB and calls it. 9, write jbosscmp-jdbc.xml, this is a CMP-specific file, which is mainly declared two big content: 1. State the correspondence between our CMP entity beans and database tables, that is, statement Which database connection pool connects to our CMP to connect to the database and which database table corresponds to. Second, declare which fields in our CMP and which fields in the database table correspond to what the correspondence between these field data types is. These steps are the necessary methods for writing and deploying CMP entity beans in JBoss, under other development platforms and different containers, we will basically write all files to make readers. Master the role of each file and field, understand these, believe that EJBs in other automated environments are very easy. Third, the example CMP entity bean writing and deployment documents, we still use the examples of the mastering ejb book to explain. Here is a little change in the examples in the book. 1. First step, we define the database table corresponding to the entity bean.

We use the MySQL database as a back library database support, and other databases are the same. We use the following SQL statements to create our database tables in a database of mysql installations: use test; drop table if EXISTS `ProductBean`; Create Table` ProductBean` (`PRODUCTID` VARCHAR (30),` Name` Varchar (120), `baseprice` Double; This data table corresponds to we will be written CMP entity bean is ProductBean. 2, set the database connection pool, please see the second series of tutorials, here, we are in JBoss's server publishing directory C: / jboss / server / all / deploy new MySQL-DS.xml file, its content As follows: mysql jdbc: MySQL: // 10.0.0.18:3306/test.com/connection-ur g< uSer-name "Root Password> Configure a MySQL database connection pool in JBOSS, the mysql database on this server 10.0.0.18, the connection port is the default 3306 port, and the connection is connected. The database is Test this library, and we specify that you can access and get a connection with the JNDI named MySQL in the EJB. 3, okay, the previous work is ready, let's write our CMP-related classes and interfaces, first we still have to build our development directory, our environment here is like this (specifically see the previous section) : Our JBOSS is installed in a C: / JBoss directory, we have built a MyProject directory below to place all our development projects. Here, we build a productcmp directory under MyProject to put our CMP. Then, in the foregoing, we built a series of directory structures in the ProductCMP directory to put our source program and release deployment files. The built-in directory structure is shown in Figure 1: Figure 1 where all of our source program is placed in the src directory, the product.jar directory puts our deployment to the CMP class in the JBoss container, and the client directory is placed in our Client test procedures related classes. Among them, all of our EJB classes are placed in a Product.EJB package. So built two layers of directories.

4, good, the directory is built, we start writing our CMP various classes and interfaces, first write the Remote interface, which is placed in the src directory, the code is as follows: //product.javaPackage product.ejb; import javax. EJB. *; import java.rmi.remoteException; public interface product extension ejbobject {// Start Get / set method, the getter / setter method name is started by Get / Set, followed by the name of the CMP // And put this name first letter uppercase, these CMP managed domains declared in EJB-JAR.XML // These methods should be exposed to remote call pUBLIC STRING GETNAME () THROWS RemoteException; public void setName (String name) throws RemoteException; public String getDescription () throws RemoteException; public void setDescription (String description) throws RemoteException; public double getBasePrice () throws RemoteException; public void setBasePrice (double price) throws RemoteException; public String getProductID () throws RemoteException; public void setProductID (String productID) throws RemoteException;} 5, and then written in the src directory Home interface, as follows: //ProductHome.javapackage product.ejb; import javax.ejb *; import java.rmi.RemoteException; import java.util.Collection. Public Interface ProductHome Extends Ejbhome {Product Create (String Product ctID, String name, String description, double basePrice) throws CreateException, RemoteException; public Product findByPrimaryKey (ProductPK key) throws FinderException, RemoteException; public Collection findByName (String name) throws FinderException, RemoteException; public Collection findByDescription (String description) throws FinderException, RemoteException; public Collection findByBasePrice (double basePrice) throws FinderException, RemoteException; public Collection findExpensiveProducts (double minPrice) throws FinderException, RemoteException; public Collection findCheapProducts (double maxPrice) throws FinderException, RemoteException;

Public Collection FindAllProducts () Throws Finderption;} In the top of the home interface, we declare a create method, which corresponds to the Ejbcreate method in the bean class we have to write, just here it returns a product object. . In the HOME interface, we also defined several lookup methods. Most of the lookup method returns to the Collection collection, because the results of the query can be multiple. These lookup methods we will describe EJB-QL in EJB-JAR.XML. 6, write primary key classes, this and BMP is the same. It reads as follows: //ProductPK.javapackage product.ejb; import java.io.Serializable; public class ProductPK implements java.io.Serializable {public String productID; public ProductPK (String productID) {this.productID = productID;} public ProductPK () {} public String toString () {return productID.toString ();} public int hashCode () {return productID.hashCode ();} public boolean equals (Object prod) {return ((ProductPK) prod) .productID . Equals (ProductID);} 7, then we must write our bean class, this class is due to the declaration of the Abstract-type Getter / Setter method, it itself needs to be declared as a Abstract type. At the same time, it does not have a way to be called by the EJB container like BMP.

Its code is as follows: package product.ejb; import javax.ejb. *; // Notice to declare as an abstract type PUBLIC Abstract Class ProductBean Implements EntityBean {Private EntityContext CTX; Public ProductBean () {} // Start Abstract Get / set method, the getter / setter method name here is started by GET / SET, followed by the CMP // of the name of the domain, and put the first letter of this name, these CMP management domains in EJB-JAR .xml declared public abstract String getName (); public abstract void setName (String name); public abstract String getDescription (); public abstract void setDescription (String description); public abstract double getBasePrice (); public abstract void setBasePrice (double price ); public abstract string getProductId (); public abstract void setProductId (String ProductID); // Start EJB Method, the method is called by the container, not being called by the client program, here only the declaration can be public void ejbactivate () { } public void ejbRemove () {} public void ejbPassivate () {} public void ejbLoad () {} public void ejbStore () {} public void setEntityContext (EntityContext ctx) {this.ctx = ctx;} public void unsetEntityContext () { THIS.CTX = CTX;} public void ejbpostcreate (String Productid, String Name, String Description, Double Basepric e) {} // This create and home interface correspondence, here it is to return a primary key class // which calls the Getter / Setter method implemented by the container to generate entity bean objects. public ProductPK ejbCreate (String productID, String name, String description, double basePrice) throws CreateException {setProductID (productID); setName (name); setDescription (description); setBasePrice (basePrice); return new ProductPK (productID);}} 8, Ok, through the above steps, we have written the class files required for CMP. Let's write the deployment descriptor file deployed by this CMP.

First, ejb-jar.xml is written, enter the meta-inflicide (ie c: /jb/myproject/productcmp/ejb/product.jar/meta-inf), create a new ejb-jar.xml file in this directory, The content is as follows: (This file is written in the file, is a self-explanatory file) Product Product.ejb.productHome Product.ejb.product Product.ejb.productbean container Product.ejb.productpk false 2.x ProductBean ProductID name description Baseprice Cmp-field> FindByname java.lang.string <

/ Method-Params> FindByDescription java.lang.string FindbyBaseprice Double FINDEXPENSIVEPRODUCTS < Method-Param> Double ? 1] ]> FindcheApproducts Double <@ Method-Param> < / method-params> FindAllProducts < Method-params> <

! [CDATA [Select Object (a) from ProductBean as a where a.productid is not null]> Product remote * Required 9, below to write JBoss-service.xml files, this file is a JBoss server-specific file, which indicates this EJB JNDI name for easy calling EJB. This file is also placed in the meta-INF directory: The content is as follows: Product Product -> TRUE 10, finally, write jbosscmp-jdbc.xml, which is a unique descriptor file deployed in JBoss, which describes entity beans and The correspondence of the database table, and it also describes the correspondence relationship between the declaration field of the entity bean maintenance and the corresponding relationship between the fields in the database table. It is also placed in the meta-inflicity, as follows, the explanation of this file I put in the file.

java: / mysql mysql True False True Foreign-key < Enterprise-Beans> Product ProductBean name name varchar varchar (60) < / cmp-field> ProductID ProductID VARCHAR <

/ jdbc-type> varchar (30) description Description Description < / column-name> varchar varchar (120) Baseprice / Field-Name> baseprice double double At this point, we have written all Java classes and deployment descriptor files required by CMP, there are three descriptor files, which can be said to implement in the BEAN class in BMP. The part now shifts to the CMP deployment descriptor file. These three descriptors are called ejb-jar.xml, jboss-service.xml, and jbosscmp-jdbc.xml files, respectively, must correspond to. And they are all placed in the MEAT-INF directory. 4. After deploying and testing CMP, after the CMP is required, let's compile, deploy and test this CMP entity bean in JBoss. First, let's write a client program that tests this CMP, enter the src directory, create a new ProductClient.java, the content is as follows: //productclient.java client test program package product.ejb; import javax.ejb. *; Import javax. naming *;. import java.rmi *;. import javax.rmi.PortableRemoteObject; import java.util *;. import java.io *;. // CMP client public class ProductClient {public static void main (String [] args THROWS EXCEPTION {ProductHome ProductHome = NULL; Try {Properties Env = New Properties (); // config.properties file should be placed in the same - level directory of the directory where the Hello package directory is located. That is, it and the Hello folder are in a folder.

Env.Load ("config.properties"); // Get a naming contextsystem.out.println (env); context ctx = new javax.naming.initialcontext (eNV); system.out.println ("got context "); // Search from jndi tree to get Home ObjectproductHome = (ProductHome) PortableRemoteObject.narrow (ctx.lookup (" Product "), ProductHome.class); // create objects productHome.create (" 123-456- 7890 "," P5-350 "," 350MHz Pentium ", 200); ProductHome.Create (" 123-456-7891 "," P5-400 "," 400MHz Pentium ", 300); Product thisproduct = ProductHome.create "123-456-7892", "P5-450", "450MHz Pentium", 400); ProductHome.Create ("123-456-7893", "SD-64", "64MB SDRAM", 50); ProductHome. Create ("123-456-7894", "SD-128", "128MB SDRAM", 100); ProductHome.Create ("123-456-7895", "SD-256", "256MB SDRAM", 200); // output product information, references thisProduct generated when you create an object System.out.println ( "thisProduct's info:" thisProduct.getProductID () thisProduct.getName () thisProduct.getDescription () thisProduct.getBasePrice ()) ; // Find a product Iterator i = ProductHome.FindByName ("SD-64"). Iterator (); System.out.println ("these Pro) ducts match the same SD-64: "); while (i.hasNext ()) {Product product = (Product) PortableRemoteObject.narrow (i.next (), Product.class); System.out.println (product.getDescription ());} // end while // Find all products of 200 yuan System.out.println ("Finding All Products That Cost1 200:"); i = productHome.FindByBaseprice (200) .Itemrator (); while (I.hasNext ()) {Product Product = (Product) PortableRemoteObject.narrow (i.next (), product.class; system.out.println;} // end while} catch Exception E) {E.PrintStackTrace ();

} finally {if (ProductHome! = NULL) {system.out.println ("delete all price> = 300 products); item i = productHome.findexpensiveProducts (300) .Itemrator (); while (I.hasNext ()) {Try {Productuct Product = (Product) PortableRemoteObject.Narrow (i.next (), product.class; product.remove ();} catch (exception e) {E.PrintStackTrace ();}} // end while} // end if} // end main} // end class then, enter the src directory, execute: com * .javacom is com.bat, is a compilation in one of our articles in this series For the batch file of the EJB class, see Section 1. After execution, it produces five Class files. Respectively the Product.classs, ProductHome.class, ProductBean.class and ProductPK.class copyed: C: /JBOSS/myproject/ProductCMP/ejb/product.jar/product/ejb directory, the Product.class, ProductHome.class, ProductPK.class and ProductClient.class file copy: c: / jboss / myproject / productcmp / ejb /client / product / ejb directory, then, then in the C: / JBoss / MyProject / ProductCMP / EJB / Client directory new creation config.properties file, as follows: java.naming.factory.initial = org.jnp.interfaces.NamingContextFactoryjava.naming.factory.url.pkgs = org.jboss.naming.clientjava.naming.provider.url = jnp: // 10.0.0.18:1099 The explanation of this file see the description in the previous section. The deployment of CMP, copy the product.jar directory into the C: / JBoss / Server / All / Deploy directory, start the JBoss server, see if there is any abnormality in the startup process. If there is no abnormality, the deployment is successful. This CMP is tested below. Enter C: / JBoss / MyProject / ProductCMP / EJB / Client Directory, execution: Runclient Product / EJB / ProductClient The screen appears as shown in Figure 2, proves that the operation is successful! Figure 2. Summary this section, we explain how to deploy and write CMP entity beans. During the actual use process, CMP is more than BMP. The key to CMP is how to handle and write deployment descriptor files.

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

New Post(0)