Tutorial for building J2ee Applications Using JBoss and Eclipse -5

xiaoxiao2021-03-06  80

CHAPTER 5.

Creating a bmp entity bean

This chapter describes how to create a Bean Managed Persistence (BMP) EJB component. We will create two BMP beans, Customer and Manager, as shown below. The Customer bean will be responsible for storing the details of customers of MyStore. The Manager bean stores Details of the Manager of MyStore. Both Beans Communicate with Their Respect Data Access Objects (DAOS) Named Customerdao and Managerdao Respective.

All customers have been assigned a unique customerID for housekeeping purposes in MyStore in addition to their username for accessing the services of MyStore. Similarly the Manager of MyStore has been assigned a unique ManagerID.

Note: It is the usual practice to access business methods of BMP beans via a session bean, which encapsulates business logic and acts as an interface to further EJB components In this case Customer and Manager are accessible via by StoreAccess..

This approach comes from a pattern called a Session Facade, whereby enterprise beans encapsulate business logic and business data and expose their interfaces. The session bean acts as a facade to encapsulate the complexity of interactions with the lower-level beans. The session facade is responsible .

THIS TUTORIAL Uses That Pattern for Business Tier Implementation.

Tasks:

Create a BMP bean named Customer under package au.com.tusc.bmp. Create a DAO class named CustomerDAOImpl under package au.com.tusc.dao. Add all attributes / properties to the CustomerBean, with getter and setter methods for each of the attributes. Add a finder method named ejbFindByPrimaryKey with the signature public CustomerPK ejbFindByPrimaryKey (CustomerPK pk) throws FinderException Add a finder method named ejbFindByUserID with the signature public CustomerPK ejbFindByUserID (String userID) throws FinderException Add a business method named getCustomerData with the signature public CustomerData getCustomerData () Implement required methods in the CustomerDAOImpl class. Deploy the Customer Bean. Add a create method to the StoreAccess Bean. public void ejbCreate () throws javax.ejb.CreateException Add a business method to the StoreAccess Bean. public CustomerData getCustomerData (String userID CREATE A TEST Client named sessionbmpclient under package au.com.tusc.client. Run Your Client and Test The Bean.create The Customer Bmp Entity Bean:

Go to Package Explorer> Expand MyStore (Project) Node> SELECT SRC, RIGHT CLICK AND A MENU WILL POP UP.

On The Pop Up Menu> New> Lomboz EJB CREATION WIZARD.

Enter package name au.com.tusc.bmp, Bean name Customer and SELECT Bean Type As Bean Manged Entity> Finish.

This Will Create a package named au.com.tusc.bmp under src and customerbean under That Package As Shown Below.

Note: It will generate the bean name, jndi-name and type of bean in file. Also, The word 'bean' is recognd to the name of the file.

As we can see from the figure above it has created a class level tag @ ejb.bean, which has assigned the bean type, its name and its JNDI name which will be generated in the Home interface. This tag will also generate deployment descriptors in ejb-jar.xml and jboss.xml file once you generate your EJB classes.Now we are going to generate all the interfaces including Home, Remote, DAO and other helper classes. We do not need to specify any tags in ejbGenerate.xml AS We Have Already Set Up That for the MyStoremgr EJB Module In Chapter 3.

Go to node customerbean under au.com.tusc.bmp> Lombozj2ee> Add ejb to module> SELECT MyStoremgr> OK.

Go to MyStoremgr Node> Lombozj2ee> Generate EJB Classes.

NOTE: All these Steps Are Covered In Previous Chapter Chapter (Chapter 3 and 1) So Please Refer to Those Sections if you need further details.

Now let's see what files are generated by xdoclet.

As shown below there are two new files named CustomerData and CustomerPK in addition to what we had for our session beans. We also have a CustomerBMP which extends our CustomerBean class. The remaining files should be familiar from our work with session beans.

As discussed in chapter 3 regading the various ejbDoclet tags used in ejbGenerate.xml, to generate these classes, CustomerData and CutomerPk are generated by following tags as shown below in this snippet from ejbGenerate.xml:

The Relevant Tags Are and .

Note: there.....................

Create Customer's Dao Interface:

Since we are going to use a DAO to access database for this bean, we have to create a DAOImpl class to provide an implementation for the generated DAO interface.Go to src> package au.com.tusc.dao> Add a class CustomerDAOImpl in That Package.

Now Go to your bean class and declare this Tag At Class Level (IE. At the top) AS Shown Below to Generate The Dao Interface.

@ ejb.dao class = "au.com.tusc.bmp.customerdao"

Impl-class = "au.com.tusc.dao.customerdaoImpl"

Regenerate your classes and check that your DAO interface is generated Note:. For reference the steps are as follows:.. Expand MyStoreMgr node under MyStore Project in Package Explorer Right click and a pop up menu will appear Go to Lomboz J2EE> Generate EJB Classes AS Shown on The Right. As Shown Below, Our Dao Interface is generated.

IT Has Four More Methods Than StoreAccess (Which Was A Stateless Session Bean) Did WHEN We first generated it (ie. Prior to adding the method @dao: cal tag).

Note: It's Worth Menting Here That Bmp Entity Beans Don't Need The @dao: Call Tag for Generating Dao Interface Methods.

All The Tag Described Earlier for Dao Interface Generation, Also Shown Below.

Also, Let's Look At The Descriptors Generated Up UxtA Step, in EJB-JAR.XML Under MyStoremgr / Meta-INF.

Thase Descriptors Are Generated by The Following Tag In Customerbean. @ Ejb.bean Name = "CUSTOMER"

JNDI-NAME = "Customerbean"

Type = "BMP" this Tag generates descriptors in jboss.xml AS Well, Which Will Be Covered Later ON.

The next step is to add attributes / properties to our Customer Bean, which will be accessible to clients through the remote interface using getter and setter methods. These attributes are mapped to corresponding columns in the relevant table in the database.In order to add these properties / attributes, define all attributes (as private to encapsulate) and their corresponding accessors / mutators (getter and setter methods). Each accessor (getter) method will have two tags or three in the case of a primary key. The mutator (setter ) Method Will Have ONLY One Tag Declared on It.

Add these Tags for Attributes / Properties (In Bean Terms) AS Shown Below.

/ ** * returns the customerid

* @Return the customerid

*

* @ Ejb.Persistence

* @ ejb.pk-field

* @ ejb.interface-method

* /

Public Java.lang.String getcustomerid () {

Return Customerid;

}

/ **

* Sets the customerid

* @Param java.lang.string the New Customerid Value

*

* @ ejb.interface-method

* /

Public void setcustomerid (java.lang.string customerid)

This.customerid = Customerid;} code snippet from CustomerBean is shown in Figure at right.

Now, Analyzing these tags,

@ Ejb.persistence specifies this as a persistent attribute. All accessor and mutator methods will be overridden in generated BMP class, in this case it is CustomerBMP, and all mutator methods will have a dirty flag in them, as persistence is controlled by ejbLoad ( ) and ejbStore (). @ ejb.pk-field specifies that this attribute is mapped to a primary key in database and and is assigned as a primary key in the PrimaryKey class, in this case the CustomerPK class. @ ejb.interface generates these Methods in The Remote Interface.

Now, in the case of mutator methods (that is 'setCustomerID') the only tag required is @ ejb.interface-method for generating this method in the remote interface.Similarly, add methods and their tags for rest of the persistent fields. There Will be no @ Ejb.pk-field tag as customerid is the primary key.

NOTE: IN The Case of a Composite Primary Key You Have To Specify @ Ejb.pk-Field Tags on The Other Attributes / Properties Which make up The composite key.

SIMILARLY, ADD TAGS AND METHODS for Rest of the Persistent Fields, Which in this Case Are, Firstname, Lastname, Address, Phone and Shareholderstatus As Shown In this code snippet from customerbean.

Generate EJB CLASSES AND EXAMINE What Methods Are Generated In The Various Classes, Particularly In CustomerBmp and CustomerData.

Add Finder Methods:

Now Let's Add a Finder Method To Our Bean Class.

Add A Method with this signature: Public Customerpk EJBFindByPrimaryKey (CustomerPK PK) THROWS FINDEREXCEPTION

Put Some Debug Statements in It and return null as shown below.

Now when we generate our EJB classes this method will be overridden in CustomerBMP. Also this method will call a corresponding method from CustomerDAO interface as shown below in this code snippet from CustomerBMP.

This will Also Create Methods in the home interface and dao interfaces as shown bell.

Add Another Finder Method to Customerbean, with the signature

Public Customerid (String Userid) THROWS FINDEREXCEPTION

Put Some Debug Statements in It and return null as shown below.

NOTE: AS Stated In The EJB SPEC 12.8.1 All Finder Methods Should Return The Primary Key.

Again, regenerate your EJB classes, and there will be methods created in the CustomerHome interface, CustomerBMP and CustomerDAO, similar to those that were created for ejbFindByPrimaryKey.A code snippet from the CustomerDAO class, after generating the EJB classes.

Add Business Methods:

NOW, Add a Business Method with the signaturepublic Customerdata getCustomerData () with interface type as local.

Note: The steps to add a business method are covered in previous chapters (1 and 3), so please refer to them Also, we have chosen the interface type to be local because these methods will be invoked in the same Java Virtual Machine.. In this case...............

This Will Provide The details of anore debug statements and return an instance of customerdata as show in this code snippet from customerbean.

Make Sure You Generate Your EJB CLASSES AGAIN Before You Start IMPLEMENTING CUSTOMER'S DAO Interface.

Implement Customer's Dao Interface:

Now Let's Implement Our Methods In CustomerDaoImpl Class.

CustomerDoaimp class under package au.com.tusc.dao imports methods generated in customerdao class under package au.com.tusc.bmp.

First Import The Following Packages.

Javax.naming.initialcontext;

Javax.sql.datasource;

Java.sql.connection;

Java.sql.preparedStatement;

Java.sql.resultset;

Java.sql.sqlexception;

Change your class declaration so what CustomerDaoImpl Implements Customerdao.

Add a field to store the JDBC Resource Factory Reference.

PRIVATE DATASOURCE JDBCFACTORY;

In the init () Method, Locate The Reference JDBC / DEFAULTDS Using The JNDI API, And Store The Reference In Variable JDBCFActory.

The lookup string is "java: comp / env / jdbc / defaultds" .code snippet is shown Below.

In method load (), first get the connection to the database using field jdbcFactory. Create a SQL statement which searches for a record corresponding to customerid in table Customer, where customerid is the primary key. Code snippet is shown below.

In method store (), first get the connection to database using field jdbcFactory. Create an SQL statement which updates a record corresponding to customerid in table Customer, where customerid is the primary key. Code snippet is shown below.

In method ejbFindByUserID (), first get the connection to database using field jdbcFactory. Create an SQL statement which searches for the customerid corresponding to a given userid in table Customer, where customerid is primary key. Code snippet is shown below.

In method ejbfindByPrimaryKeystore (), first get the connection to database using field jdbcFactory. Create an SQL statement which searches for customerid in table Customer, where customerid is the primary key. Return the primary key. Code snippet is shown below.

Also, You Should Implement Methods Remove and Create. We're Leaving Those As an EXERCISE for You (You've Probably Got The Idea By Now!), Or You Can Leave The as Stubs as Shown Below.

Nowur CustomerDaoImpl Class is Finished. Generate Your EJB Classes Again.

After Generating Your EJB Classes, Let's Look At The Remote Local Interface.

In the Remote Local Interface (which is CustomerLocal in this case), there is one business method exposed, and the rest are all the methods to access the attributes / properties of the bean (as we also declared these methods as interface methods in CustomerBean) , as shown below. These methods are generated by @ ejb.interface-method tag.In the Home Local Interface, which is CustomerLocalHome in this case, there are two finder methods as shown below. It has also generated JNDI_NAME and COMP_NAME (logical name To lookup the component.

The Following Tag Declared In Customerbean as Shown Below.

Note: We are not currently interested in the Customer interface (which is a Remote interface) and CustomerHome (which is a Remote Home interface), because we are accessing bean methods in the same Java Virtual Machine, so we need only Local interfaces.

NOTE: IN Customerbean We Haven't Implement Any Methods for the Setting and Unsetting of Context, Because It Is Generated by xdoclet in The customerBmp Class, as shown bellow.

Now Customer Bean and Its Dao Implementation IS Complete and We CAN Deploy this bean.

Deploy Customer Bean:

In Order to Deploy this Bean We Have to Add A Few Deployment Descriptors to It. We will add the two. We will address.

First Add The Tag Shown Below At Class Level In Customerbean.

@ ejb.resource-ref res-ref-name = "jdbc / defaultds"

Res-Type = "javax.sql.datasource"

Res-auth = "container"

This tag will generate deployment descriptors in ejb-jar.xml, as the bean has to know which datasource you are going to connect to, and what is its ts type, etc. This will generate these descriptors as shown below.

Add this second tag required for the jboss application server. @ Jboss.resource-ref res-name = "jdbc / defaultds"

JNDI-Name = "Java: / Defaultds"

THIS TAG WILL Generate Deployment Descriptors in jboss.xml, As the application Server Has To Know with what jndi-name the Datasource Has Been Registered with. This Will Generate The Descriptors as shown Below.

Now everything is completion, and it's time to deploy the bean. So, regenerate your ejb classes.

Note: As Nonded In Earlier Chapter and Over To Properly Illustrate Each Step and Its Result. Once You Are Proficient You Will Be Aable To Forgo Most of this.

Go to Lomboz J2EE View> Expand Node MyStore> Expand MyStoremgr> SELECT 'JBOSS 3.2.1 All'.

Right Click> SELECT 'DEBUG Sever' on Pop Up Menu.

Note: this is to start your server, if you are away.

Go to MyStoremgr Node in Lombozj2ee View> Right Click> SELECT 'Deploy' on pop up menu as shown Figure below.

NOTE: All these Techniques Have BEEN Shown In Previous Chapter CHAPTERS (1 and 3) So Please Refer to the.

.......................... ...CRIPLILE, THE.

Now Our Customer Bean Is Complete, And in Order To Create a Client To Invoke Operations On This Bean We Have Make Some Modifications To Our StoreAccess Bean.

Note: As shown in the diagram at the beginning of this chapter that client will invoke operations on Customer Bean through Store AccesBean, as it is a good practice to access Entity Beans in this manner As a result we need a Local view of Customer Bean. Rather Than Remote, Both Are In The Same Java Virtual Machine.Add Create Method in StoreAccess:

In StoreAccess Bean Add An Ejbcreate Method, Which Will Create a Bmp Entity Bean with the following signalure

Public void ejbcreate () THROWS JAVAX.EJB.CREATEXCEPTION

Now, Add A Field To Store The Reference Obtained by Locating Customer in JNDI.

Private Customerlocalhome CustomerLocalhome;

In Ejbcreate Method Store The Reference In The CustomerlocalHome Variable by Invoking The GetLocalHome Static Method In Customerutil Class As Shown In The Code Snippet Below from storeAccess bean.

Add Business Method in StoreAccess:

Add ANOTHER Business Method in StoreAccess Bean Which Will Invoke The Corresponding Business Method on Customer Bean.

Now, add a business method with this signature public CustomerData getCustomerData (String userID) with Interface type as Remote. As customers will log on to MyStore with username, once they are authenticated they will be identified by userid and they can retrieve their account details from MyStore Using this userid.

NOTE: Steps to create Business Methods Are Covered in Previous Chapter.

Now Invoke One of the Finder Methods of Customer On The Reference Variable We Have Created In The EJBCREATE METHOD.

CustomerLocal MyCustomer = CustomerLocalHome.FindByUserid (userID)

Now Invoke The Business Method on Customer Using The MyCustomer Reference Variable.

CustomerData CD = MyCustomer.getCustomerData () Code Snippet of this Business Method is shown Below.

All methods in StoreAccess Bean have now been added for the accessing the Customer's business method. All that remains are the deployment descriptors required for linking / referencing the StoreAccess and Customer beans. We will add the two tags shown below.

First Add this Tag At Class Level in StoreAccess Bean.

@ Ejb.ejb-ref ejb-name = "Customer"

View-type = "local"

Ref-name = "CustomerLocal"

This tag will generate deployment descriptors in ejb-jar.xml, as StoreAccessBean has to know which bean it's referring to, and what is its view-type and ref-name. This will generate these descriptors as shown below.

Note: View type is local as both are in the same Java Virtual Machine, otherwise it would be Remote Note that ref-name is generated as CustomerLocalHome rather than CustomerHome Both are generated but we are using Local in this case...

Now Add the second tag shown below at class level in storeAccess bean.

@ jboss.ejb-ref-jndi ref-name = "CustomerLocal"

JNDI-Name = "CustomerLocal"

THIS TAG WILL Generate Deployment Descriptors in jboss.xml, as the application server has to know what JNDI-Name Customer Bean Has Been Registered With. This Will Generate these Descriptors as shown Below.

NOTE: REF-NAME AND JNDI-NAME ARE Used for Bean As Local (In Same JVM).

Note:. As we can see from the code snippet above, the deployment descriptor generated by tag @jboss is wrong, because for local referencing of Customer tag should be There seems to be a bug in this tag, so we will correct this manually by changing the tag in the jboss.xml file as shown below.Caution here: Make sure that you do this change manually after you finish regenerating your EJB classes, because every time you regenerate your Classes, 'JBoss.xml' Will Initially Have The Wrong Descriptor.

Now our changes to StoreAccess Bean are complete, so deploy your bean again now from the Lomboz J2EE View. The steps to do that are shown above and in previous chapters. Messages will appear in the console showing the status of deployment.

ONCE YOUR BEAN IS Deployed Success, Create A Test Client Which Will Invoke The LoginUser Method on StoreAccessBean and getCustomerData on CustomerBean.

Create Your Test Client:

Go to Project MyTStore Node> Select Src Node Abd Expand It> Select Au.com.Tusc.Client Package> Right Click.

Select New On POP Up Menu> Select Lomboz EJB Test Client Wizard.

NOTE: THESE Steps Are Covered in Previous Chapter.

Select package name au.com.tusc.client, name as SessionBMPClient and select Ejb Home as au.com.tusc.session.StoreAccessHome and Ejb Interface as au.com.tusc.session.StoreAccess as shown in figure below.

This will be in your sessionBmpClient class and you simply the loginuser and getcustomerData Methods as shown.

Now to add some code to your client.

Add these Lines Under The TestBean Method As Shown Below.

System.out.println ("Request from Cliant:");

String userid = mybean.loginuser ("andy", "passwd");

System.out.println ("Reply from Server: Your Userid IS" UserID;

CustomerData CD = MyBean.getCustomerData (userID);

System.out.println ("Andy Your Details with MyStore Are" CD);

Test Your Client:

Now, in Order to Test your client, Select SessionBmpClient Node> Go at top level menu and select the 'man running' icon.

On That Select 'Run As'> Select Java Application, AS Shown Below.

Now Under Your Console, IF Your Reply for 'Andy' IS 'U2', And His Details for Customerid Are 'C2' AS Well, The Your Call Is Successful (See Below).

EXERCISE:

Here is an esrcise for you. To Progress Further, Implement Manager as a bmp Entity Bean Similar To Customer, with The Same Behaviours. The detaild tasks are given below.

Create a BMP Bean named Manager under package au.com.tusc.bmp. Create a DAO class named ManagerDAOImpl under package au.com.tusc.dao. Add all attribute / properties in ManagerBean, add accessor and mutator methods for each attribute. Add a find method named ejbFindByPrimaryKey with signature public ManagerPK ejbFindByPrimaryKey (MangerPK pk) throws FinderException. Add a find method named ejbFindByUserID with signature public MangerPK ejbFindByUserID (String userID) throws FinderException Add a business method named getManagerData with signature public ManagerData getManagerData () Implement methods in ManagerDAOImpl class Lookup string required for JNDI API is... "java: comp / env / jdbc / DefaultDS" Deploy Manager Bean Add a field in StoreAccess Bean to store reference after lookup in JNDI for Manager private ManagerLocalHome managerLocalHome; in ejbCreate method of StoreAccess Bean Store Reference In ManagerLocalhome Variable by Invoking GetLocalHome Static Method in ManagerUtil. Add a business method in StoreAccess Bean. Public MangerData getManagerData (String userID) Add the following tags for deployment at class level for linking / referencing Manager.1. @ Ejb.ejb-ref ejb-name = "Manager" view-type = " Local

Ref-name = "managerlocal"

2. @ jboss.ejb-ref-jndi ref-name = "managerlocal"

JNDI-Name = "ManagerLocal" test your manager bean by running your test client create for customer named sessionbmpclient.

Note: Don't forget to fix the generated descriptors in jboss.xml as personned Above in relation to customer bean.

.

In case you're unable to do that, we have provided ManagerBean, ManagerDAOImpl, modified StoreAccessBean and modified SessionBMPClient classes You can download these files from downloads below.Downloads.:

Managerbean

ManagerdaoImpl

StoreAccessBean

SessionBmpClient

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

New Post(0)