站内搜索: 请输入搜索关键词

当前页面: 开发资料首页J2EE 专题Tutorial for building J2EE Applications using JBOSS and ECLIPSE (5)

Tutorial for building J2EE Applications using JBOSS and ECLIPSE (5)

摘要: Tutorial for building J2EE Applications using JBOSS and ECLIPSE (5)

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 respective tables in the database using Data Access Objects (DAOs) named CustomerDAO and ManagerDAO respectively.






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 for managing business objects and provides a uniform business service abstraction to presentation layer clients, thereby hiding the business object implementation in the lower-level beans.

This tutorial uses that pattern for business tier implementation.

Tasks :

  1. Create a BMP bean named Customer under package au.com.tusc.bmp.

  2. Create a DAO class named CustomerDAOImpl under package au.com.tusc.dao.

  3. Add all attributes/properties to the CustomerBean, with getter and setter methods for each of the attributes.

  4. Add a finder method named ejbFindByPrimaryKey with the signature

    public CustomerPK ejbFindByPrimaryKey (CustomerPK pk) throws FinderException

  5. Add a finder method named ejbFindByUserID with the signature

    public CustomerPK ejbFindByUserID (String userID) throws FinderException

  6. Add a business method named getCustomerData with the signature

    public CustomerData getCustomerData()

  7. Implement required methods in the CustomerDAOImpl class.

  8. Deploy the Customer Bean.

  9. Add a create method to the StoreAccess Bean.

    public void ejbCreate() throws javax.ejb.CreateException

  10. Add a business method to the StoreAccess Bean.

    public CustomerData getCustomerData(String userID)

  11. Create a test client named SessionBMPClient under package au.com.tusc.client.

  12. 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 appended 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 don't 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 chapters (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 is no CustomerDAO class, as we haven't generated that file by specifying the dao tag in the CustomerBean class.

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"





<table cellSpacing=2 cellPadding=3 width="100%" border=0> <thEAD> <tr vAlign=top> <td width=469>

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.



</td> <td width=473>







</td></tr></thEAD> </table>


If we look at the generated DAO class as shown below, 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 level @dao:call tag).

Note : It's worth mentioning here that BMP Entity beans don't need the @dao:call tag for generating DAO interface methods.




All these methods are generated by the tag described earlier for DAO interface generation, also shown below.



Also, let's look at the descriptors generated up until this step, in ejb-jar.xml under MyStoreMgr/META-INF.

<table cellSpacing=4 cellPadding=4 width="100%" border=0> <thEAD> <tr vAlign=top> <td width="57%">

These 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.

</td> <td width="43%">



</td></tr></thEAD> </table>



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.

<table cellSpacing=0 cellPadding=4 width=975 border=0> <thEAD> <tr vAlign=top> <td width=503>

/**

    * 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.

</td> <td width=456>



</td></tr></thEAD> </table>

Now, analyzing these tags,

  1. @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().

  2. @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.

  3. @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 below.





Add another finder method to CustomerBean, with the signature


public CustomerPK ejbFindByUserID (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 signature

public 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 they will be invoked by the stateless bean StoreAccess.

This will provide the details of an individual customer. Add some debug statements and return an instance of CustomerData as shown below 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 implements 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 that 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 them as stubs as shown below.




Now our CustomerDAOImpl class is finished. Generate your EJB classes again.

After generating your EJB classes, let's look at the Home Local Interface and 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).


These names are generated by 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 implemented any methods for the setting and unsetting of context, because it is generated by Xdoclet in the CustomerBMP class, as shown below.


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 tags shown below.


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-ref-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 these descriptors as shown below.




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

Note : As noted in earlier chapters we are regenerating classes over and over to properly illustrate each step and its result. Once you are proficient you will be able 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 already running your server then skip these steps and go to the next one.

Go to MyStoreMgr node in LombozJ2EE view > right click > select 'Deploy' on pop up menu as shown in figure below.




Note : All these techniques have been shown in previous chapters (1 and 3) so please refer to them.

The messages in the console will show whether your bean has been successfully deployed or not.

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, because 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 (in this case a Customer Bean) with the following signature

public void ejbCreate () throws  javax.ejb.CreateException 

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 chapters.

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 descriptors generated by this tag.

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 successfully, 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 chapters.

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 generate required methods for you in your SessionBMPClient class and you simply invoke 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 client : ");

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, then your call is successful (see below).




Exercise :

Here is an exercise for you. To progress further, implement Manager as a BMP Entity bean similar to Customer, with the same behaviours. The detailed tasks are given below.

  1. Create a BMP Bean named Manager under package au.com.tusc.bmp.

  2. Create a DAO class named ManagerDAOImpl under package au.com.tusc.dao.

  3. Add all attribute/properties in ManagerBean, add accessor and mutator methods for each attribute.

  4. Add a find method named ejbFindByPrimaryKey with signature

    public ManagerPK ejbFindByPrimaryKey (MangerPK pk) throws FinderException.

  5. Add a find method named ejbFindByUserID with signature

    public MangerPK ejbFindByUserID (String userID) throws FinderException

  6. Add a business method named getManagerData with signature

    public ManagerData getManagerData()

  7. Implement methods in ManagerDAOImpl class. Lookup string required for JNDI API is "java:comp/env/jdbc/DefaultDS".

  8. Deploy Manager Bean.

  9. Add a field in StoreAccess Bean to store reference after lookup in JNDI for Manager

    private ManagerLocalHome managerLocalHome;

  10. In ejbCreate method of StoreAccess Bean store reference in managerLocalHome variable by invoking getLocalHome static method in ManagerUtil.

  11. Add a business method in StoreAccess Bean.

    public MangerData getManagerData(String userID)

  12. 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" 
  13. Test your Manager Bean by running your Test Client created for Customer named SessionBMPClient.

Note : Don't forget to fix the generated descriptors in jboss.xml as mentioned above in relation to Customer Bean.

Note : All these steps are the same as those for Customer. Implement this Bean which will be used in subsequent chapters.

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




↑返回目录
前一篇: Tutorial for building J2EE Applications using JBOSS and ECLIPSE(4)
后一篇: Tutorial for building J2EE Applications using JBOSS and ECLIPSE (6)