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
    Business professionals no longer wonder if they'll migrate to the cloud; it's now a matter of when. The cloud environment has proved to be a major force in transitioning to an agile business model that enables quick decisions and fast implementation that solidify customer relationships. And when the cloud is combined with the power of cognitive computing, it drives innovation and transformation that achieves astounding competitive advantage.
    Machine learning has taken residence at our cities' cores and now we can finally have "smart cities." Cities are a collection of buildings made to provide the structure and safety necessary for people to function, create and survive. Buildings are a pool of ever-changing performance data from large automated systems such as heating and cooling to the people that live and work within them. Through machine learning, buildings can optimize performance, reduce costs, and improve occupant comfort by ...
    René Bostic is the Technical VP of the IBM Cloud Unit in North America. Enjoying her career with IBM during the modern millennial technological era, she is an expert in cloud computing, DevOps and emerging cloud technologies such as Blockchain. Her strengths and core competencies include a proven record of accomplishments in consensus building at all levels to assess, plan, and implement enterprise and cloud computing solutions. René is a member of the Society of Women Engineers (SWE) and a m...
    Early Bird Registration Discount Expires on August 31, 2018 Conference Registration Link ▸ HERE. Pick from all 200 sessions in all 10 tracks, plus 22 Keynotes & General Sessions! Lunch is served two days. EXPIRES AUGUST 31, 2018. Ticket prices: ($1,295-Aug 31) ($1,495-Oct 31) ($1,995-Nov 12) ($2,500-Walk-in)
    According to Forrester Research, every business will become either a digital predator or digital prey by 2020. To avoid demise, organizations must rapidly create new sources of value in their end-to-end customer experiences. True digital predators also must break down information and process silos and extend digital transformation initiatives to empower employees with the digital resources needed to win, serve, and retain customers.
    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...
    Digital Transformation: Preparing Cloud & IoT Security for the Age of Artificial Intelligence. As automation and artificial intelligence (AI) power solution development and delivery, many businesses need to build backend cloud capabilities. Well-poised organizations, marketing smart devices with AI and BlockChain capabilities prepare to refine compliance and regulatory capabilities in 2018. Volumes of health, financial, technical and privacy data, along with tightening compliance requirements by...
    Charles Araujo is an industry analyst, internationally recognized authority on the Digital Enterprise and author of The Quantum Age of IT: Why Everything You Know About IT is About to Change. As Principal Analyst with Intellyx, he writes, speaks and advises organizations on how to navigate through this time of disruption. He is also the founder of The Institute for Digital Transformation and a sought after keynote speaker. He has been a regular contributor to both InformationWeek and CIO Insight...
    Digital Transformation is much more than a buzzword. The radical shift to digital mechanisms for almost every process is evident across all industries and verticals. This is often especially true in financial services, where the legacy environment is many times unable to keep up with the rapidly shifting demands of the consumer. The constant pressure to provide complete, omnichannel delivery of customer-facing solutions to meet both regulatory and customer demands is putting enormous pressure on...
    Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settlement products to hedge funds and investment banks. After, he co-founded a revenue cycle management company where he learned about Bitcoin and eventually Ethereal. Andrew's role at ConsenSys Enterprise is a mul...