Home > Articles > Programming > Java

The Java Developers' Introduction to XDoclet

Want a great timesaver when working with EJB development? With XDoclet you can create EJBs, SessionBeans, and MessageBeans without having to create interfaces, XML descriptors, or server-specific files. Go step by step with Marcus Zarra through the basic implementation of XDoclet.
Like this article? We recommend

Most of the instructions that exist on the net for XDoclet read like stereo instructions. They provide a tremendous amount of information, but it is scattered and disjointed—they don't give you a clear picture of how to use this tool. To clear up the confusion, this article outlines the base needed to get started using XDoclet. I will be using JBoss as the example application server to code against.

First, let me discuss the tools I will use. To make this tutorial as generic as possible, I do not use any specific IDE. Feel free to use whatever is your preference. All the examples detailed below can be written in any plain text editor: Notepad, vi, emacs, or something more complicated. To work along with these examples, you should download and set up the following tools:

NOTE

The installation and setup instructions for these tools are beyond the scope of this article. There are Readme documents provided with each tool to help you.

Entity Bean

Let's dive right in and start with an entity bean. First, here is the code for an entity bean without XDoclet (I am detailing only the bean itself; not any of the interfaces):

package com.dzrealms.example.entity;

import javax.ejb.EntityBean;
import javax.ejb.EntityContext;
import javax.ejb.RemoveException;
import javax.ejb.CreateException;

public abstract class ExampleBean implements EntityBean {

  public Integer ejbCreate() throws CreateException {
   return null;
  }

  public void ejbPostCreate() {

  }

  public abstract Integer getID();
  public abstract void setID(Integer i);
  public abstract String getName();
  public abstract void setName(String s);
  public abstract String getValue();
  public abstract void setValue(String s);

  public void setEntityContext(EntityContext context) {
  }

  public void unsetEntityContext() {
  }

  public void ejbRemove() throws RemoveException {
  }

  public void ejbActivate() {
  }

  public void ejbPassivate() {
  }

  public void ejbLoad() {
  }

  public void ejbStore() {
  }
}

This bean is not very special. It has a default creation method, an ID to be used as the primary key, a name, and a value. Normally, to create this EJB by hand, we would have to create at least one home interface and one reference interface—both of them being either remote or local. In addition, we would have to create or update the application.xml and the server-specific xml files to be able to utilize this bean. That's a lot of work!

With XDoclet, we will eliminate all that work. Although it requires the bean itself to be a bit more complex, the overall amount of work required is dramatically reduced.

Let's break down the components of XDoclet. XDoclet works by placing reading a set of javadoc tags in the source code and then generating the appropriate interfaces and xml files. These tags can get quite complex because there is a large amount of configurability available. The tags come in two flavors: method level tags and class level tags. The method level tags are just what the name suggests—they define information about a specific method. The class level tags do the bulk of the work so therefore we will tackle them first.

Class Level Tags

Here's what the class level tags for my ExampleBean class look like:

/**
 * @ejb.bean name="ExampleBean"
 *      jndi-name="example/remote/ExampleBean"
 *      local-jndi-name="example/local/ExampleBean"
 *      cmp-version="2.x"
 *      primkey-field="ID"
 *      schema="Example"
 *
 * @ejb.persistence table-name="example"
 *
 * @ejb.interface remote-class="com.dzrealms.example.entity.ExampleRemote"
 *        local-class="com.dzrealms.example.entity.ExampleLocal"
 *
 * @ejb.home remote-class="com.dzrealms.example.entity.ExampleHomeRemote"
 *      local-class="com.dzrealms.example.entity.ExampleHomeLocal"
 *
 * @jboss.entity-command name="mysql-get-generated-keys"
 * 
 * @jboss.unknown-pk class="java.lang.Integer"
 *          auto-increment="true"
 */

This is the least amount of information needed for XDoclet to function properly. These tags detail the local and remote JNDI names, the names of all of the homes, and the interfaces for this bean.

@ejb.bean

Name

This tag is the name of the bean, which is used in references for relationships and used by XDoclet to supply the name of the bean in the descriptors. The name you choosecan be anything you want, but it must be unique to the application.

jndi-name

This tag is rolled up with the name tag. Generally, each tag that has the same prefix can be rolled up together, but there are a few exceptions to this rule (I will point out these exceptions as they occur).

The jndi-name tag specifies the jndi name of the remote home reference. This is the name used to get a reference to the remote home of this bean for creation and lookups.

local-jndi-name

This tag specifies the jndi name of the local home reference. This name is used to get a reference to the remote home of the bean for creation and lookups.

cmp-version

This tag informs XDoclet which version of Container Managed Persistence is to be used with the bean. This information is used in the construction of the descriptors.

Primkey-field

This tag specifies which field is the primary key. Using the rules of JavaBeans, the primary key methods are resolved from this name. In our example, the primary key is specified as "ID"; therefore, the methods getID and setID will get and set the primary key.

Schema

This tag specifies the schema for this bean. The schema is used by Java's enterprise query language.


@ejb.persistence

table-name

This tag specifies the name of the table associated with this bean. The table name does not have to match the bean name and normally it doesn't match. Although this tag can be omitted, it is not recommended.


@ejb.interface

remote-class

This tag tells XDoclet what to name the interface to be used as the remote interface for the bean. The fully qualified package name is required.

local-class

This tag tells XDoclet what to name the interface to be used as the local interface for the bean. The fully qualified package name is required.


@ejb.home

remote-class

This tag tells XDoclet what to name the class to be used as the remote home for the bean. The fully qualified package name is required.

local-class

This tag tells XDoclet what to name the class to be used as the local home for the bean. The fully qualified package name is required.


@jboss.entity-command

Because I am using JBoss as my application server, I need to tell XDoclet how to handle the generation of primary keys. This tag tells XDoclet to add mysql-get-generated-keys as the key generator. This will be added to the jboss specific descriptors.

@jboss.unknown-pk

Again, because I am using JBoss, I need to tell JBoss via XDoclet what the primary key is and whether or not it is auto-incremented. This tag handles that for me.

Class

tag The class of the primary key.

auto-increment

tag Whether or not the database will handle incrementing the primary key


Method Tags

The tags listed above are the only tags that are required for a bean to be built properly by XDoclet. However, without methods, a bean is fairly useless. For each method that you want exposed in an interface, certain tags are required. The following sections describe the tags required based on method type.

Create Method

Create methods require one tag to be generated correctly. This tag has a default value that allows you to make it very simple. The following is an example of the tag required for the no parameter create method:

 /**
  * @ejb.create-method
  * @return Primary Key
  * @throws CreateException
  */ 
  public Integer ejbCreate() throws CreateException {
   return null;
  }

  public void ejbPostCreate() {

  }

The post create does not require any tags, and the ejbCreate method requires only the ejb.create-method tag. This tag can be further defined to control which home it is displayed in, but that is beyond the scope of this document.

Select Method

To create a select method within a bean, a single tag is required. This tag defines the query used in the select method:

 /**
  * @ejb.select query="select o.ID from Example o where o.name = ?1"
  * @param s Name we are searching with
  * @return Set of Primary Keys with that name
  * @throws FinderException
  */ 
  public abstract Set ejbSelectByName(String s) throws FinderException;

The query follows the rules for the Enterprise Query Language.

Bean Methods

The last types of methods that are generated are the bean methods. Normally these are getter and setter methods that represent a column in a table in the database. They can also be concrete methods that perform some form of business function on the bean itself. Both types of methods are defined the same way:

 /**
  * @ejb.interface-method
  * @ejb.persistence
  * @return the name of this bean
  */
  public abstract String getName();
  /**
  * @param s Set the name of this bean
  */
  public abstract void setName(String s);
  /**
  * @ejb.interface-method
  * @ejb.persistence
  * @return the value of this bean
  */
  public abstract String getValue();
  /**
  * @ejb.interface-method
  * @param s Set the value of this bean
  */
  public abstract void setValue(String s);

For a method to be displayed in the interface (either remote or local) the tag @ejb.interface-method needs to be added to that method's javadoc, which informs XDoclet to add the method to the available interfaces. Without this tag, the method is still available to the bean and therefore the container will not be exposed to the interfaces. I can define the name field as read-only. The set method does not contain the @ejb.interface-method tag; therefore, only the container can call this method.

The other tag shown is @ejb.persistence, which tells XDoclet that this getter refers to a persistence method. Every column that is to be populated into the bean needs to have this tag applied to the associated getter. If the name of the column in the database does not match the name of the field in the bean, the tag needs to be further defined:

  * @ejb.persistence column-name="COLUMN_NAME"

If the column-name tag is not included, XDoclet assumes that the column name is the same as the field name.

Ant Task

With the first bean now defined, it's time to create an Ant task to generate all the interfaces for me. The task for XDoclet is not built into Ant, so I have to define it. Here is the entire Ant build file that will execute XDoclet on the bean (this Ant file works on the assumption that all the source code is stored in a directory called src):

<project name="example" default="all" basedir=".">

  <property file="${user.name}.properties"/>
  <path id="xdoclet.classpath">
   <fileset dir="${xdoclet.home}/lib">
    <include name="*.jar"/>
   </fileset>
   <pathelement location="${j2ee.jar}"/>
   <fileset dir="${jboss.home}/server/default/lib">
    <include name="*.jar"/>
   </fileset>
  </path>

  <path id="classpath">
   <pathelement location="${j2ee.jar}"/>
  </path>

  <taskdef name="ejbdoclet" classname="xdoclet.modules.ejb.EjbDocletTask"
   classpathref="xdoclet.classpath"/>

  <target name="all">
   <mkdir dir="gen"/>
   <ejbdoclet destdir="gen" ejbspec="2.0">
    <fileset dir="src">
     <include name="**/*.java"/>
    </fileset>
    <remoteinterface/>
    <homeinterface/>
    <localinterface/>
    <localhomeinterface/>
    <deploymentdescriptor destdir="META-INF"/>
    <jboss version="3.2" datasource="java:/example-ds"
     datasourcemapping="oracle"
     destdir="META-INF" xmlencoding="UTF-8"/>
   </ejbdoclet>
   <mkdir dir="classes"/>
   <javac debug="true" destdir="classes">
    <src path="src"/>
    <src path="gen"/>
    <classpath refid="classpath"/>
   </javac>
  </target>
</project>

The first component of this build file is a property tag that tells Ant to load additional properties from another file that is named by the logged-in user. This other file merely points out specific locations of where XDoclet and JBoss are installed. My properties file would look like this:

xdoclet.home=/Users/mzarra/Development/Libraries/xdoclet-1.2.2
jboss.home=/opt/jboss

The next tag builds a classpath using the path tag. Using the locations specified in the property file tag, the classpath is defined with all the jars in the server lib directory and XDoclet's lib directories. I have also created another classpath that has only the j2ee jar in it. This second classpath will be using for compiling all of source code. For compiling the XDoclet libraries are unnecessary. If the project were to require additional libraries, I would add them to this second path.

The taskdef tag defines the actual XDoclet tag. Using the classpath defined above, the task ejbdoclet is defined so that it can be used in targets.

The final tag is the actual target. This tag first creates the gen directory in which the generated source code will be stored. Next, it executes the ejbdoclet task that was defined previously. The task itself requires the following parameters:

Destdir

This is the directory in which the generated source code will be placed. In this example, the directory is named gen.

Ejbspec

This is the spec that XDoclet will generate the source code to. In this example, I am using 2.0.


Inside of the ejbdoclet tag, there are additional subtasks that define what is to be generated. In this example, I have added tags to generate remote home interfaces, remote interfaces, local interfaces, local home interfaces, and deployment descriptors. There is also a tag specifying which application server I am using. If I add more servers here, the server-specific deployment descriptors for these servers will also be generated.

The final task compiles all the source code from the two source directories: It places the compiled code into a classes directory. Executing the default task generates all the source code and deployment descriptors.

NOTE

The only remaining item is building the ear file for deployment. That task is outside of the scope of this document.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020