Creating Container-managed Entity Beans with JBoss and MyEclipse

written by aext on July 19, 2008 in Tutorials with 6 comments
Introduction

An Entity Bean is an Enterprise JavaBean (EJB) that represents a persistent object in a relational database. JBoss provides two methods of entity bean persistence, Bean Managed Persistence (BMP) and Container-Managed Persistence (CMP). With BMP, the entity bean developer must implement all the persistence logic. With CMP, the application server manages entity bean persistence; the developer provides interfaces and configuration.

Entity JavaBeans that use container-managed persistence (CMP) are convenient, because they require so little custom code to achieve automatic persistence. But that convenience carries a price: beans using CMP are also ferociously complex to configure, and often difficult to debug.

Preparing

There’re many ways to create EJB with CMP method. But, why we not make it simply by using MyEclipse? In this article, you will see how can i make an CMP in MyEclipse and Jboss step by step. So, you have to install pre-requirements to make it works. I’m using:

  • Eclipse 3.2.1 with MyEclipse 5.5.1 GA
  • Database MSSQL 2000 with services pack 3 (so easily config in tutorial), you can use any SQL server you want.
  • Java SE 5.0 with Update 10 (the old version of Java SE, lastest realease is Java SE 6 Update 10 Beta)
  • jboss-4.0.5.GA

You sould create a working directory where you install and store all related files. In this tutorial we’ll use C:Java as working directory. If you want to store it somewhere else, then you’ll have to replace every occurence of “C:Java” throughout the tutorial by the desired directory.

Download and install Java SE JDK

You can download the lastest version of Java SE JDK is Java SE 6 JDK in Java SE download page. I’m still using Java Se 5 JDK :D

  1. Pick the latest JDK without Java EE SDK and/or Netbeans. (so, we not need NetBean for whatever :D)
  2. Accept the License Agreement and click at Windows Offline Installation, Multi-language.
  3. You will get the file jdk-xxx-windows-i586-p.exe (xxx base on your version downloaded), save it to disk.
  4. Install the JDK and JRE in C:Java .Default path for install is C:Program Filesjava. You should change to C:java because when using command, you not need to add double quote to java path.

Download and install Eclipse 3.2 with MyEclipse 5.5.1 GA

Eclipse is fee :D. You should download the lastest Eclipse IDE package Eclipse IDE for Java EE Developers

  1. Surf to the Eclipse download page.
  2. Click at Eclipse IDE for Java EE Developers.
  3. Select a mirror and you will get the file eclipse-jee-ganymede-win32.zip, save it to disk.
  4. Extract the zip to your work directory.

Well, you can download one package include Eclipse and MyEclipse at MyEclipse Download Page by Accept License Agreement: Standard/Pro License and Blue Edition License. Please download Eclipse IDE 3.2.x same as my tutorial.

  1. See MyEclipse Enterprise Workbench 5.5.1 GA for Windows 98/2000/NT/XP/Vista (05/21/2007)
  2. Choose All In One Package if you want to install MyEclipse Full Package includes Eclipse or Plug-in if want MyEclipse Standalone.
  3. Install IDE or Plug-In.
Download jboss

Download lastest version of jboss if you want or jboss version 4.0.5 GA same as mine at JBoss Application Server Downloads

Extract the package to your work directory. Done.

Install Microsoft SQL Server with Services Pack 3 (or above)

If you installed MS SQL 2000 server, you have to install services pack 3 to work with JNDI Datasource. Download the services pack at MS SQL 2000 Server with Services Pack 3a download page.

Important: You must upgrade computers running Microsoft® Windows® XP to Windows XP Service Pack 1 before applying SQL Server 2000 Service Pack 3a.

Run and configure Eclipse

  1. The first time to start Eclipse, you must select work space for Eclipse.
  2. On the welcome screen, click at the icon with the curved arrow at the right side: Go to the workbench
  3. In the top menu, go to Window » Preferences » Java » Installed JREs. Select the current JRE (it should automatically be the same as you have installed, but we not use jre as JRE Installed, should edit it to JDK directory, in this case, click jre which automatically add to Eclipse and Edit, point the directory to JDK installed directory, and it’ll automatically known what directory where jre is. Now the source code of the Java SE API is available in Eclipse.

Integrate JBoss in Eclipse

In the top menu, go to Window » Preferences » MyEclipse » Application Servers » Jboss 4. Select Enable Jboss Server, select Jboss Home Directory, others field is default. Then select JDK, choose JDK you installed, click Apply, then Ok. Now Jboss is integrated in Eclipse.

On the Toolbar of Eclipse, click  and select JBoss server to start jboss. Default port of jboss is 8080(keep in mind), you can change it later. Once it is started, go to http://localhost:8080 (where 8080 is supposed to be the HTTP/1.1 port of Tomcat). You should get the default Jboss home page.

You can simply stop jboss server by click on

Create EJB project with CMP method

In the menu, click File » New » Project...In the New Project Dialog, select MyEclipse, then choose EJB Project:

Click next to continues. Then enter the EJB project details, i choose the name as “CMPTutorial”, click finish.

Ok, you prepared an EJB project, now, to create new CMP method, right click on Project at Package Eplorer panel, select New »Other…Choose MyEclipse in Wizard Dialog and select EJB » Entity Bean, click next as image below

In Entity Bean Diaplog image above, you can see the red ellip. Note: the name of package must be end with ejb folder and the class name must be end with Bean. Example, if your package is “yourpackage” the entity bean must be in “yourpackage.ejb” and the name of class entity bean of yours is YourBean or AnythingBean….Access of the EJB can be Remote/Local or Both, i select Remote in order to access from outside EJB.

Click Finish.

The Entity Bean Class

The entity bean class contains the entity bean logic. However, with CMP, the entity class is abstract, because many of the methods are defined in the class but implemented by the container. Accessor methods must be both public and abstract and the name of every method defined in CMP must be exactly with database field name.

In database:

In Entity Bean class:

/**
* @ejb.interface-method view-type="both"
* @ejb.pk-field
* @ejb.persistence
* @jboss.persistence
*    not-null = "true"
*    auto-increment = "true"
* @jboss.sql-type
*   type = "int"
* @jboss.jdbc-type
*      type = "INTEGER"
* @return
*/
public abstract Integer getArticle_ID();
/**
* @ejb.interface-method view-type="both"
* @param article_ID
*/
public abstract void setArticle_ID(Integer article_ID);

/**

* @ejb.persistence-field
* @ejb.interface-method view-type="remote"
* @return
*/

public abstract String getArticle_title();

/**
* @ejb.interface-method view-type="both"
* @param article_title
*/
public abstract void setArticle_title(String article_title);

/**
* @ejb.persistence-field
* @ejb.interface-method view-type="remote"
* @return
*/
public abstract String getArticle_desc();

/**
* @ejb.interface-method view-type="both"
* @param article_desc
*/
public abstract void setArticle_desc(String article_desc);

/**
* @ejb.persistence-field
* @ejb.interface-method view-type="remote"
* @return
*/
public abstract String getArticle_content();

/**
* @ejb.interface-method view-type="both"
* @param article_content
*/
public abstract void setArticle_content(String article_content);

So, because in database, the primary field is article_ID, the getArticle_ID must be declared as pk-field and if it’s auto-increment, you have to add @jboss.persistence with not-null=”true” and auto-increment = “true”. Each method getter in Entity Bean class have to be added in the top with the following: @ejb.persistence-field and @ejb.interface-method view-type=”remote” and each method setter, must be: @ejb.interface-method view-type=”both”.

Add following codes into the top of class:

/**
*
* @ejb.bean name="Article"
*           display-name="Name for Article"
*           description="Description for Article"
*           jndi-name="ejb/Article"
*           type="CMP"
*           cmp-version="2.x"
*           view-type="remote"
*           schema="ArticlesSchema"
*           primkey-field="article_ID"
*           primkey-class="java.lang.Integer"
*
* @ejb.pk class = "java.lang.Integer"  generate = "False"
*
* @jboss.unknown-pk class="java.lang.Integer"
*      column-name="article_ID"
*      jdbc-type="INTEGER"
*      sql-type="int"
*      auto-increment="true"
* @jboss.entity-command name="mssql-fetch-key"
*
* @ejb.finder query="SELECT OBJECT(b) FROM ArticlesSchema AS b"
*    signature="java.util.Collection findAll()"
*
* @ejb.finder query="SELECT OBJECT(b) FROM ArticlesSchema AS b WHERE b.article_ID=?1"
*    signature="java.util.Collection findByArticleId(java.lang.Integer article_ID)"
*
* @ejb.persistence table-name="Articles"
* @jboss.persistence table-name="Articles"
*/
public abstract class UsersCMPBean implements EntityBean {

External clients use an entity bean’s home interface to create, remove, and find instances of the entity bean. In Entity Bean class defines the following methods:

  • Create. Creates an entity bean instance.
  • Remove. (required) Removes an entity bean instance.
  • Finder methods. Find one or more entity bean instances. Finder method names must start with “find” (which i’ve defined in the top of the class above). For a CMP entity bean, the finder method findByPrimaryKey must be defined, but with MyEclipse, findByPrimaryKey method will be automatically generated by XDoclet.

In Entity Bean class, search for ejbCreate() method, replace by:

public Integer ejbCreate(String article_title, String article_desc, String article_content) throws CreateException {
    setArticle_title(article_title);
    setArticle_desc(article_desc);
    setArticle_content(article_content);
    return null;
}

Becasue article_ID is primary field and it’s auto-increment, so you not need to set Article_ID in ejbCreate. Note: ejbCreate() method must return to primary value type(in above, primary field is article_ID, and the value type is Integer, sql-type and jdbc-type are different).

Replace ejbPostCreate() method by:

public void ejbPostCreate(String article_title, String article_desc, String article_content) throws CreateException {
}

The entity Bean Provider may use the ejbPostCreate() to set the values of cmr-fields to complete the initialization of the entity bean instance. An ejbPostCreate() method executes in the same transaction context as the previous ejbCreate() method.

Add Standard EJB module to XDoclet project properties

To generate EJB related classes using XDoclet, you have to add Standard EJB module to XDoclet project properties. Right click on Project, click on Properties. Choose MyEclipse » XDoclet. In Configuration tab, click Add Standard…, select Standard EJB, click OK.

Customize XDoclet configuration

Right click on Standard EJB was defined above, choose Add(not Add Doclet), select jboss, click OK to add jboss entity.

You can customize XDoclet with some value in order to generate EJB related classes

    1. dir: src
    2. includes: **/*.java
  • deloymentDescription
    1. destDir :src/META-INF
    2. validateXML: true
  • fileset
  • jboss

    1. version: 4.0
    2. alterTable: false
    3. creatTable: false;
    4. datasource: java:/Articles
    5. datasourceMapping: MS SQLSERVER2000
    6. destDir :src/META-INF

Following entities are required, you can remove others.

Run XDoclet

We have not completely finished the source code, but it is time for a first generation with xdoclet.

Right click on the project and choose run xdoclet.

Create JNDN Datasource

Create new XML file and deploy(simply save XML file to Jboss directoryserverdefaultdeploy) with name: xxx-ds.xml and inlcudes following codes:

<datasources>
  <local-tx-datasource>
    <jndi-name>Articles</jndi-name>
    <connection-url>jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=YourDatabase</connection-url>
    <driver-class>com.microsoft.jdbc.sqlserver.SQLServerDriver</driver-class>
    <user-name>username</user-name>
    <password>password</password>

    <metadata>
    <type-mapping>MS SQLSERVER2000</type-mapping>
    </metadata>
  </local-tx-datasource>
</datasources>
Deploy EJB to Jboss server

Right click in Project, select MyEclipse » Add and Remove Project Deployments… Following these steps below:

When completed, in console window announ that Bound EJB Home ‘Article’ to jndi ‘ejb/Article’. That’s all, you have created new EJB with CMP method successfully.

For the next article, i’ll guide you how to access EJB with Java Application and Java Web Aplication

Best Rigard!

© 2008, Nguyen, Lam Duy