Welcome!

Weblogic Authors: Yeshim Deniz, Elizabeth White, Michael Meiner, Michael Bushong, Avi Rosenthal

Related Topics: Weblogic

Weblogic: Article

Using EJBGen

Using EJBGen

Sick of working with all of those different Java files and deployment descriptors when developing EJBs for WebLogic Server? A couple of tools out there allow you to work with just the bean code, and use special Javadoc comments to define what should be in the other interfaces (Home, Remote), and the XML deployment descriptors (ejb-jar.xml, weblogic-ejb-jar.xml). After using these tools, you quickly realize how clean it is to just have one Java source file representing your EJB.

Introducing EJBGen
In this article we'll look at a tool for generating WebLogic 6.1-compatible EJBs, EJBGen, that was developed by Cedric Beust, a BEA WebLogic architect (www.beust.com/cedric/ejbgen). It can easily be added to your WebLogic build process and is IDE neutral - you just add Javadoc tags in your bean class. Unfortunately, the tool is closed source, since it was developed solely by Cedric, but he is accessible once you join the mailing list. Requests are made, bugs are found, and Cedric fixes them in short order. If you need an open source solution, then you can use XDoclet (http://sourceforge.net/projects/xdoclet), which is derived from EJBDoclet, written by JBoss creator Rickard Oberg.

In this article, I create a set of WebLogic 6.1 deployable EJBs representing a simple Order system. There will be two entity beans, which represent an order and its items. These will use EJB 2.0 CMP relationships, allowing us to get access to the items from the order itself. We'll have a session bean that manipulates these entity beans to get work done.

Using EJBGen
At a simple level, EJBGen allows you to place information about your EJBs in Javadoc tags, which are embedded in the bean class. The special tags are formatted as follows:

/**
* @ejbgen:tagname attribute = value attribute2 = value2 ...
*/
These @ejbgen tags are placed either at the class level, or at the method level, depending on the type of tag. At the class level you can declare the EJB's name, the JNDI name, and attributes for the entire bean. The method level attributes flag information on the given method. The most common tag you'll use is for the method to be part of a Remote or Local interface (using @ejbgen:remote-method, or @ejbgen:local-method).

/**
* @ejbgen:remote-method
*/
public String viewMaxOrders() {
After your bean classes have been created, and the Javadoc tags have been plugged in, you can run EJBGen through your Javadoc client:

% javadoc -docletpath /path/to/ejbgen.jar
-doclet EJBGen YourEJBs.java
There are also command line options that tweak the way EJBGen generates its files. Many of them allow you to change the prefixes and suffixes of the various elements.

To generate a remote interface named FooRemote.java instead of Foo.java, you would run the following command (note the -remoteSuffix):

% javadoc -docletpath ejbgen.jar -doclet EJBGen
-remoteSuffix Remote FooEJB.java
The full set of command line options are documented on the EJBGen site.

EJBGen Features
EJBGen also has the following features:

  • Fully EJB 2.0 compliant (local interfaces/ CMP relationships/message driven beans)
  • Generates WebLogic 6+ deployable code and deployment descriptors
  • Can generate Value objects for the Entity Beans
  • Property files: properties can be defined and used inside the bean class. A property is used via ${ property name }
  • Supports Javadoc tag inheritance. A base adapter class can set a standard values, then your actual bean inherits the behavior, as well as the methods
  • Generates ANT build files

    If you generate an ANT build file, after running EJBGen, you can run

    % ant -buildfile ejbgen-build.xml
    You can tweak variables such as:

  • ant.buildFileName: Name of the buildfile
  • ant.projectName: Name of the project
  • ant.docletPath: Path to ejbgen.jar Creating a Session Bean That Uses Javadoc Tags Now let's get into the real example, starting with the session bean that manipulates the entity beans. The OrderViewerEJB.java will hold the following methods:
  • viewMaxOrders(): Returns the maximum orders, which will be an <env-entry>, to show how we set them up in the class-level javadoc comment
  • viewOrders(): Returns the orders in the system
  • addOrder(orderId, orderBy, orderName): Inserts the order entry
  • addOrderItem(orderID, itemID, itemName, amount): This will insert an item for the given order
  • deleteOrders(): Deletes all of the orders and items within the orders

    Class-Level Definitions
    At the class level, we need to define the fact that this is a session bean, and information relevant to that: the JNDI name; EJB local references to the entity beans; and environment entries.

    Tag: @ejbgen:session
    The only required attribute here is to tell EJBGen the name of the bean. We'll also define the maximum beans in the free pool (WebLogic caching info), and that the default transaction attribute will be "Required."

    /**
    * OrderViewer Bean views orders:
    *
    * @ejbgen:session
    * ejb-name = OrderViewer
    * max-beans-in-free-pool = 100
    * default-transaction = Required
    *
    * ... other tags ...
    */
    public class OrderViewerEJB implements SessionBean {
    The full set of attributes for the ejbgen:session tag is shown in Table 1.

    Tag: @ejbgen:jndi-name
    This tag is very important; not only does it define the JNDI names, but EJBGen also uses it to know whether to generate a remote interface, a local interface, both, or neither! Since we want to expose the session bean to remote clients, we'll use the remote attribute:

    /**
    * OrderViewer Bean views orders:
    *
    * ... other tags ...
    *
    * @ejbgen:jndi-name
    * remote = ejbgenexamples.OrderViewer
    *
    * ... other tags ...
    */
    public class OrderViewerEJB implements SessionBean {
    For a local interface we would add the attribute "local = local-jndi-name."

    Tag: @ejbgen:ejb-local-ref
    Our OrderViewer will use the entity beans that represent an order, and an order item. EJB 2.0 introduced the idea of "local interfaces" which force the components to "talk" in the local VM, not across remote boundaries. When working with entity beans, it's a good practice to have session beans (which are remote capable) work with entity beans locally. We'll define the two local references to the two entity beans (Listing 1). With these local references, we can get access to the Home interface by looking up "java: comp/env/ <name>" to look up the OrderLocal Home:

    OrderLocalHome orderHome = (OrderLocalHome) new
    InitialContext().lookup("java:/comp/env/ejb/Order-Home");
    To reference EJBs with remote contracts, use the @ejbgen:ejb-ref tag.

    Tag: @ejbgen:env-entry
    To define environment entries you use the ejbgen:env-entry tag. We'll define an environment entry to hold the integer value of the maximum orders:

    /**
    * OrderViewer Bean views orders:
    *
    * ... other tags ...
    *
    * @ejbgen:env-entry
    * name = maxOrders
    * type = java.lang.Integer
    * value = 10
    *
    * ... other tags ...
    */
    public class OrderViewerEJB implements SessionBean {
    The type must always be fully qualified (java. lang.Integer, not Integer).

    Method Level Definitions
    We want to tag all of the methods that we want available to a remote client. As an option, you can also pass in values for the transaction attribute of the method (i.e., override the default value that we set up at the class level) and the isolation level. Here we tag the addOrder() method:

    /**
    * Add an order
    *
    * @ejbgen:remote-method
    */
    public void addOrder(Integer id, String orderBy, String name)
    We'll see that the entity beans will tag their methods @ejbgen:local-method. Now our session bean is good to go!

    Creating the OrderItem Entity Bean
    Working with entity beans is similar to working with session beans. There are a couple of different class level tagsp; we'll flag the fields that the container should manage, and the primary key. We'll generate an OrderItem entity that includes three fields - itemid, itemname, and itemamount - that will persist.

    The database table will also contain an ORDER_ID that's a foreign key into the Order entity (discussed later). For now, we'll ignore the fact that the OrderItem will have a relationship with an Order.

    Class Level Definitions
    At the class level, we will define the entity definition, the JNDI name, and the entity finder signature, and we'll create the tables in the DB.

    Tag: @ejbgen:entity
    As with the session bean, we need to define the name of the entity bean and can define attributes like the default transaction value. We also need to define the name of the table in the database, the primary key class, and the data source to use:

    /**
    * @ejbgen:entity
    * ejb-name = OrderItemEJB
    * data-source-name = orderPool
    * table-name = OrderItems
    * prim-key-class = java.lang.Integer
    * default-transaction = Required
    *
    * ... other tags ...
    */
    public abstract class OrderItemEJB implements EntityBean {
    The full set of attributes for the ejbgen:entity tag are shown in Table 2.

    Tag: @ejbgen:jndi-name
    This is identical to the session, but since we're using entities we'll create only a local interface:

    /**
    * ... other tags ...
    *
    * @ejbgen:jndi-name
    * local = ejbgenexamples.OrderItemLocalHome
    *
    * ... other tags ...
    Tag: @ejbgen:finder
    Every finder method must have an ejbgen:finder tag. You must specify the method signature, including any exceptions that you may want to throw. Also, pass in the EJB Query Language that you wish to use. We'll define a findItemsByName() method that retrieves every item with a given name:

    /**
    * @ejbgen:finder
    * signature = "Collection findItemsByName(String name)"
    * ejb-ql = "WHERE name = ?1"
    Tag: @ejbgen: create-default-dbms-tables
    For development it's nice to have WebLogic create the database tables for you:

    * @ejbgen:create-default-dbms-tables
    Method Level Definitions
    All of the abstract get() methods must be flagged as container-managed persistence fields, and we give the column name mapping. The primary key must be flagged, and if we want to be able to call these methods from a component interface, we must flag that too (remote or local). Here's the primary key for the OrderItem:

    /**
    * @ejbgen:cmp-field column = id
    * @ejbgen:local-method
    * @ejbgen:primkey-field
    */
    public abstract Integer getId();
    public abstract void setId(Integer id);
    Creating the Order Entity Bean, and Relating It to the OrderItem
    WebLogic 6.1 supports EJB 2.0 relationships, a feature not seen in many other J2EE servers. WebLogic, however, has no deployment descriptor tools to deploy your CMP relationship entities (XML must be manually manipulated), so we'll use EJBGen's features to accomplish this.

    We'll have a one-to-many relationship in which an order can have multiple items within it. From the order, we'll be able to get a Collection of items via getItems(), and from an item we can get back to the order via OrderLocal getOrder(). As well as defining these abstract methods, we need to configure ejbgen:relation tags in each class (Order-EJB, and OrderItemEJB). The steps for this relationship are:

    1. OrderItem: Configure ejbgen:relation tag
    2. OrderItem: Create container managed relationships
    3. Order: Configure ejbgen:relation tag
    4. Order: Create container managed relationships
    OrderItem: Configure ejbgen:
    relation tag

    This item is the "many" side of the relationship. Both sides of the relationship share the same name, and the target-ejb is the name of the bean for which this relationship is to be used. Since we have the target-ejb attribute, you could place all relation tags in one EJB bean class if you wanted to. Since our multiplicity is many, we will tell EJBGen the foreign key column and the field that maps to the container-managed relationship. When an order is deleted, we want the items to be deleted automatically, which is where the cascade-delete option comes in:

    * @ejbgen:relation
    * multiplicity = many
    * name = OrderCanHaveMultipleItems
    * target-ejb = OrderItemEJB
    * fk-column = order_id
    * cmr-field = order
    * cascade-delete = True
    OrderItem: Create container managed relationships
    We can get to the order from an item within this order. We tag the CMR field and declare it as a local method:

    /**
    * @ejbgen:cmr-field
    * @ejbgen:local-method
    */
    public abstract OrderLocal getOrder();
    public abstract void setOrder(OrderLocal order);
    Order: Configure ejbgen: relation tag
    This order is the "one" side of the relationship. The relation has to have the same relation name:

    * @ejbgen:relation
    * multiplicity = one
    * name = OrderCanHaveMultipleItems
    * target-ejb = OrderEJB
    Order: Create container managed relationships
    Since an order has many items, we work with a Collection of OrderItems:

    /**
    * @ejbgen:cmr-field
    * @ejbgen:local-method
    */
    public abstract Collection getItems();
    public abstract void setItems(Collection items);
    If you've ever worked with CMP relationships then you may have cursed a few times. However, EJBGen makes CMP relationships in WebLogic rather easy. I'd never want to build the XML for the relationships manually. I want to use a GUI to build my relationships, or I can use EJBGen. To take EJBGen a step further, there are GUIs that build EJBGen-aware classes. Check out the freeware Middlegen (http://boss.bekk.no/boss/middlegen/).

    Deploying the System
    Now we have three Java source files: OrderEJB.java, OrderItemEJB.java, and OrderViewerEJB.java. From these we'll use EJBGen to generate the interfaces and XML deployment descriptors. Here's a build script that will package an ejb-jar file:

    javadoc -docletpath c:\ejbgen\ejbgen.jar
    -doclet EJBGen ejbgenexamples\Order*EJB.java
    cd ejbgenexamples
    javac -classpath %CLASSPATH%;.. *.java
    cd ..
    mv *.xml META-INF
    jar cvf c:\bea\wlserver6.1\config\
    mydomain\applications\ejbgen.jar *
    We must have a data source configured in the application server - under the name "orderPool" - before the application can be run. It would also help to have a client, which can run the methods on the OrderViewer session bean. Listing 2 shows the main() method of a client that adds, views, and then deletes an order containing a couple of items.

    Summary
    We've seen how to develop EJBs for WebLogic 6.1 using EJBGen. This tool allows us to have one file to worry about per EJB rather than three Java files and multiple descriptors. It's a nice clean preprocessing system - and there are even other tools that can generate EJBGen-aware code! EJBGen is a winner for any WebLogic development environment.

  • More Stories By Dion Almaer

    Dion Almaer is a principal technologist for The Middleware Company (
    www.middleware-company.com), one of the nation's
    leading training companies in EJB/J2EE and B2B
    technology training. The Middleware Company also
    built and maintains TheServerSide.com, the
    leading online J2EE community.

    Comments (0)

    Share your thoughts on this story.

    Add your comment
    You must be signed in to add a comment. Sign-in | Register

    In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


    IoT & Smart Cities Stories
    IoT is rapidly becoming mainstream as more and more investments are made into the platforms and technology. As this movement continues to expand and gain momentum it creates a massive wall of noise that can be difficult to sift through. Unfortunately, this inevitably makes IoT less approachable for people to get started with and can hamper efforts to integrate this key technology into your own portfolio. There are so many connected products already in place today with many hundreds more on the h...
    DXWorldEXPO LLC, the producer of the world's most influential technology conferences and trade shows has announced the 22nd International CloudEXPO | DXWorldEXPO "Early Bird Registration" is now open. Register for Full Conference "Gold Pass" ▸ Here (Expo Hall ▸ Here)
    With 10 simultaneous tracks, keynotes, general sessions and targeted breakout classes, @CloudEXPO and DXWorldEXPO are two of the most important technology events of the year. Since its launch over eight years ago, @CloudEXPO and DXWorldEXPO have presented a rock star faculty as well as showcased hundreds of sponsors and exhibitors! In this blog post, we provide 7 tips on how, as part of our world-class faculty, you can deliver one of the most popular sessions at our events. But before reading...
    Machine Learning helps make complex systems more efficient. By applying advanced Machine Learning techniques such as Cognitive Fingerprinting, wind project operators can utilize these tools to learn from collected data, detect regular patterns, and optimize their own operations. In his session at 18th Cloud Expo, Stuart Gillen, Director of Business Development at SparkCognition, discussed how research has demonstrated the value of Machine Learning in delivering next generation analytics to impr...
    The Internet of Things will challenge the status quo of how IT and development organizations operate. Or will it? Certainly the fog layer of IoT requires special insights about data ontology, security and transactional integrity. But the developmental challenges are the same: People, Process and Platform and how we integrate our thinking to solve complicated problems. In his session at 19th Cloud Expo, Craig Sproule, CEO of Metavine, demonstrated how to move beyond today's coding paradigm and sh...
    @DevOpsSummit at Cloud Expo, taking place November 12-13 in New York City, NY, is co-located with 22nd international CloudEXPO | first international DXWorldEXPO and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The widespread success of cloud computing is driving the DevOps revolution in enterprise IT. Now as never before, development teams must communicate and collaborate in a dynamic, 24/7/365 environment. There is no time t...
    What are the new priorities for the connected business? First: businesses need to think differently about the types of connections they will need to make – these span well beyond the traditional app to app into more modern forms of integration including SaaS integrations, mobile integrations, APIs, device integration and Big Data integration. It’s important these are unified together vs. doing them all piecemeal. Second, these types of connections need to be simple to design, adapt and configure...
    In his session at 21st Cloud Expo, Raju Shreewastava, founder of Big Data Trunk, provided a fun and simple way to introduce Machine Leaning to anyone and everyone. He solved a machine learning problem and demonstrated an easy way to be able to do machine learning without even coding. Raju Shreewastava is the founder of Big Data Trunk (www.BigDataTrunk.com), a Big Data Training and consulting firm with offices in the United States. He previously led the data warehouse/business intelligence and Bi...
    Contextual Analytics of various threat data provides a deeper understanding of a given threat and enables identification of unknown threat vectors. In his session at @ThingsExpo, David Dufour, Head of Security Architecture, IoT, Webroot, Inc., discussed how through the use of Big Data analytics and deep data correlation across different threat types, it is possible to gain a better understanding of where, how and to what level of danger a malicious actor poses to an organization, and to determ...
    To Really Work for Enterprises, MultiCloud Adoption Requires Far Better and Inclusive Cloud Monitoring and Cost Management … But How? Overwhelmingly, even as enterprises have adopted cloud computing and are expanding to multi-cloud computing, IT leaders remain concerned about how to monitor, manage and control costs across hybrid and multi-cloud deployments. It’s clear that traditional IT monitoring and management approaches, designed after all for on-premises data centers, are falling short in ...