Tutorial for building J2EE Applications using JBOSS and ECLIPSE -5

原创 2004年08月30日 17:34:00

Chapter 5.

blurulr6.gif

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.



J2EECaseStudyFlowDiagram.png


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.

CustomerBmp.png
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.

CustomerSrcWithoutDAO.png
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/>.

ejbGeneratePkTag.png
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.

CustomerDAOImpl.png


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.



CustomerBeanDAOTag.png



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.


CustomerDAO.png

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

CustomerDAOTag.png

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



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.

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.

CustomerBeanAttributes.png

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.

CustomerBeanEjbFind.png

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.


CustomerBMPjbFind.png

This will also create methods in the Home interface and DAO interfaces as shown below.

CustomerHomeFindBy.png

CustomerDAOFindBy.png

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.

CustomerBeanFindByUserID.png
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.

CustomerDAOFindByUserID.png

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.

CustomerBeanGetCustomerData.png

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.





Change your class declaration so that CustomerDAOImpl implements CustomerDAO.

Add a field to store the JDBC resource factory reference.


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.

CustomerDAOImplInit.png


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.

CustomerDAOImplLoad.png


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.

CustomerDAOImplStore.png


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.

CustomerDAOImplFindByUserID.png


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.

CustomerDAOImplFindBy.png
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.

CustomerBeanRemove.png


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.

CustomerLocal.png


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

CustomerLocalHome.png
These names are generated by the following tag declared in CustomerBean as shown below.

CustomerBeanNameTag.png


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.

CustomerBmpEntityContext.png
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.

CustomerBeanDeploymentTags.png
First add the tag shown below at class level in CustomerBean.


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.

ejbJarDSTag.png


Add this second tag required for the JBOSS application server.


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.

jbossDDTag.png


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.

LombozJ2EEViewCustomerBeanDeploy.png


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


Now, add a field to store the reference obtained by locating Customer in JNDI.


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.

StoreAccessBeanEjbCreate.png


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.

         

Now invoke the business method on Customer using the myCustomer reference variable.


Code snippet of this business method is shown below.



StoreAccessBeanGetCustomerData.png


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.

StoreAccessBeanDDTag.png


First add this tag at class level in StoreAccess Bean.

 
 

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.

ejbjarwithStoreAccess.png
Now add the second tag shown below at class level in StoreAccess Bean.


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

jbossWithStoreAccessWrong.png


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.

jbossWithStoreAccess.png
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.

TesTClientCreateEJB.png
This will generate required methods for you in your SessionBMPClient class and you simply invoke the loginUser and getCustomerData methods as shown.

TestClientGeneratedView.png


Now to add some code to your client.

Add these lines under the testBean method as shown below.




TesTClientCode.png


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.

TesTClientRun.png


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

TesTClientResult.png


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.

         
         
     
    
          
  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

Eclipse配置JBoss的方法

第一次接触JBoss,突然让把项目部署到JBoss上,有点不知所错,以下是自己经过半天的倒腾,理的思路。 Eclipse配置JBoss的方法:(基本和tomcat相似)   1)首先要JDK的安装...
  • nikita_wxb
  • nikita_wxb
  • 2014年09月12日 17:21
  • 4794

Eclipse上设置Jboss的发布路径

1.点击Window --->  Preferences  --->  Server  ---->  Runtime Environme 2.点击add按钮,选择相应的服务器 3.选择安装路径及相...
  • Howie_zhw
  • Howie_zhw
  • 2016年05月13日 09:12
  • 2715

J2ee项目从0搭建(一):eclipse下载、安装、使用习惯配置迁移

JDK安装我们默认已经安装好了,推荐JDK1.7以上。 1.eclipse下载:在eclipse官网下载最新版本,http://www.eclipse.org/downloads/:在这里我们选择...
  • u010246789
  • u010246789
  • 2016年06月02日 11:12
  • 1677

eclipse building workspace太慢或者 js出错问题解决

1.js文件错误解决办法   右键项目->properties->Builders(注:JavaScript Validator也会引起 build workspace太慢)   ...
  • crazzy0727
  • crazzy0727
  • 2016年11月03日 14:42
  • 3616

Java EE开发环境的配置(eclipse Jboss MySQL)

Java EE开发环境的配置 本文中Java EE开发环境的配置以32位Windows XP操作系统为例。 1.1 JDK 7安装与配置 在Oracle官方网站下载JDK 7u45(网址为http...
  • lyh_66_
  • lyh_66_
  • 2016年12月27日 14:36
  • 1822

eclipse+Jboss配置远程调试

开发中,往往发布的应用与开发环境的环境有差异,测试环境报的问题在开发环境很难重现,也很难定位问题,如果报错,是程序问题还是环境问题,常常是让开发头痛的事。 拿我们项目来说,测试环境用的服务器是J...
  • coolcoffee168
  • coolcoffee168
  • 2015年09月16日 11:20
  • 1741

[Eclipse] - 集成JBoss7热加载和自动发布

使用Eclipse + JBoss开发时,总是要重启项目或JBoss,烦人。下面方法可以很简单的实现Eclipse + JBoss热加载和自动发布。 我的环境是JBoss 7.1.1 Final ...
  • haitaofeiyang
  • haitaofeiyang
  • 2017年04月19日 15:32
  • 565

jboss 在eclipse环境下 远程debug调试 测试用例

1、在eclipse中新建名字叫“webtest”的web应用,里面包含一个简单的HelloServlet,web.xml和HelloServlet.java的内容如下。 2...
  • chenb365
  • chenb365
  • 2016年12月20日 14:40
  • 484

eclipse在线安装JBoss Tool过程

eclipse在线安装JBoss Tool过程 1、打开eclipse,依次点击“help--->Install New Software...” 2、再单击“Add”按钮,弹出输入框,Nam...
  • you23hai45
  • you23hai45
  • 2014年04月06日 20:51
  • 2921

Eclipse标准版如何安装J2EE插件?Eclipse安装J2EE插件教程

Eclipse标准版如何安装J2EE插件?Eclipse安装J2EE插件教程 www.111cn.net 编辑:edit02_lz 来源:转载 Eclipse是一个基于Java的开...
  • evilcry2012
  • evilcry2012
  • 2015年06月19日 15:40
  • 4166
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Tutorial for building J2EE Applications using JBOSS and ECLIPSE -5
举报原因:
原因补充:

(最多只允许输入30个字)