分享
 
 
 

Tutorial for building J2EE Applications using JBOSS and ECLIPSE -5

王朝java/jsp·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

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 :

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 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 <dataobject/> and <entitypk/>.

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"

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.

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.

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.

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 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 <ejb-ref> should be <ejb-local-ref>. 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.

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

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
2023年上半年GDP全球前十五强
 百态   2023-10-24
美众议院议长启动对拜登的弹劾调查
 百态   2023-09-13
上海、济南、武汉等多地出现不明坠落物
 探索   2023-09-06
印度或要将国名改为“巴拉特”
 百态   2023-09-06
男子为女友送行,买票不登机被捕
 百态   2023-08-20
手机地震预警功能怎么开?
 干货   2023-08-06
女子4年卖2套房花700多万做美容:不但没变美脸,面部还出现变形
 百态   2023-08-04
住户一楼被水淹 还冲来8头猪
 百态   2023-07-31
女子体内爬出大量瓜子状活虫
 百态   2023-07-25
地球连续35年收到神秘规律性信号,网友:不要回答!
 探索   2023-07-21
全球镓价格本周大涨27%
 探索   2023-07-09
钱都流向了那些不缺钱的人,苦都留给了能吃苦的人
 探索   2023-07-02
倩女手游刀客魅者强控制(强混乱强眩晕强睡眠)和对应控制抗性的关系
 百态   2020-08-20
美国5月9日最新疫情:美国确诊人数突破131万
 百态   2020-05-09
荷兰政府宣布将集体辞职
 干货   2020-04-30
倩女幽魂手游师徒任务情义春秋猜成语答案逍遥观:鹏程万里
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案神机营:射石饮羽
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案昆仑山:拔刀相助
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案天工阁:鬼斧神工
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案丝路古道:单枪匹马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:与虎谋皮
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:李代桃僵
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:指鹿为马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:小鸟依人
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:千金买邻
 干货   2019-11-12
 
推荐阅读
 
 
 
>>返回首頁<<
 
靜靜地坐在廢墟上,四周的荒凉一望無際,忽然覺得,淒涼也很美
© 2005- 王朝網路 版權所有