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.


    @ThingsExpo Stories
    The 22nd International Cloud Expo | 1st DXWorld Expo has announced that its Call for Papers is open. Cloud Expo | DXWorld Expo, to be held June 5-7, 2018, at the Javits Center in New York, NY, brings together Cloud Computing, Digital Transformation, Big Data, Internet of Things, DevOps, Machine Learning and WebRTC to one location. With cloud computing driving a higher percentage of enterprise IT budgets every year, it becomes increasingly important to plant your flag in this fast-expanding busin...
    Smart cities have the potential to change our lives at so many levels for citizens: less pollution, reduced parking obstacles, better health, education and more energy savings. Real-time data streaming and the Internet of Things (IoT) possess the power to turn this vision into a reality. However, most organizations today are building their data infrastructure to focus solely on addressing immediate business needs vs. a platform capable of quickly adapting emerging technologies to address future ...
    Nordstrom is transforming the way that they do business and the cloud is the key to enabling speed and hyper personalized customer experiences. In his session at 21st Cloud Expo, Ken Schow, VP of Engineering at Nordstrom, discussed some of the key learnings and common pitfalls of large enterprises moving to the cloud. This includes strategies around choosing a cloud provider(s), architecture, and lessons learned. In addition, he covered some of the best practices for structured team migration an...
    No hype cycles or predictions of a gazillion things here. IoT is here. You get it. You know your business and have great ideas for a business transformation strategy. What comes next? Time to make it happen. In his session at @ThingsExpo, Jay Mason, an Associate Partner of Analytics, IoT & Cybersecurity at M&S Consulting, presented a step-by-step plan to develop your technology implementation strategy. He also discussed the evaluation of communication standards and IoT messaging protocols, data...
    With tough new regulations coming to Europe on data privacy in May 2018, Calligo will explain why in reality the effect is global and transforms how you consider critical data. EU GDPR fundamentally rewrites the rules for cloud, Big Data and IoT. In his session at 21st Cloud Expo, Adam Ryan, Vice President and General Manager EMEA at Calligo, examined the regulations and provided insight on how it affects technology, challenges the established rules and will usher in new levels of diligence arou...
    In his Opening Keynote at 21st Cloud Expo, John Considine, General Manager of IBM Cloud Infrastructure, led attendees through the exciting evolution of the cloud. He looked at this major disruption from the perspective of technology, business models, and what this means for enterprises of all sizes. John Considine is General Manager of Cloud Infrastructure Services at IBM. In that role he is responsible for leading IBM’s public cloud infrastructure including strategy, development, and offering m...
    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 B...
    Recently, REAN Cloud built a digital concierge for a North Carolina hospital that had observed that most patient call button questions were repetitive. In addition, the paper-based process used to measure patient health metrics was laborious, not in real-time and sometimes error-prone. In their session at 21st Cloud Expo, Sean Finnerty, Executive Director, Practice Lead, Health Care & Life Science at REAN Cloud, and Dr. S.P.T. Krishnan, Principal Architect at REAN Cloud, discussed how they built...
    22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud ...
    22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud ...
    DevOps at Cloud Expo – being held June 5-7, 2018, at the Javits Center in New York, NY – announces that its Call for Papers is open. Born out of proven success in agile development, cloud computing, and process automation, DevOps is a macro trend you cannot afford to miss. From showcase success stories from early adopters and web-scale businesses, DevOps is expanding to organizations of all sizes, including the world's largest enterprises – and delivering real results. Among the proven benefits,...
    @DevOpsSummit at Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, is co-located with 22nd Cloud Expo | 1st DXWorld Expo 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 to wait...
    Cloud Expo | DXWorld Expo have announced the conference tracks for Cloud Expo 2018. Cloud Expo will be held June 5-7, 2018, at the Javits Center in New York City, and November 6-8, 2018, at the Santa Clara Convention Center, Santa Clara, CA. Digital Transformation (DX) is a major focus with the introduction of DX Expo within the program. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive ov...
    SYS-CON Events announced today that T-Mobile exhibited at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. As America's Un-carrier, T-Mobile US, Inc., is redefining the way consumers and businesses buy wireless services through leading product and service innovation. The Company's advanced nationwide 4G LTE network delivers outstanding wireless experiences to 67.4 million customers who are unwilling to compromise on qua...
    SYS-CON Events announced today that Cedexis will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Cedexis is the leader in data-driven enterprise global traffic management. Whether optimizing traffic through datacenters, clouds, CDNs, or any combination, Cedexis solutions drive quality and cost-effectiveness. For more information, please visit https://www.cedexis.com.
    SYS-CON Events announced today that Google Cloud has been named “Keynote Sponsor” of SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Companies come to Google Cloud to transform their businesses. Google Cloud’s comprehensive portfolio – from infrastructure to apps to devices – helps enterprises innovate faster, scale smarter, stay secure, and do more with data than ever before.
    SYS-CON Events announced today that Vivint to exhibit at SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California. As a leading smart home technology provider, Vivint offers home security, energy management, home automation, local cloud storage, and high-speed Internet solutions to more than one million customers throughout the United States and Canada. The end result is a smart home solution that sav...
    SYS-CON Events announced today that Opsani will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Opsani is the leading provider of deployment automation systems for running and scaling traditional enterprise applications on container infrastructure.
    SYS-CON Events announced today that Nirmata will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Nirmata provides a comprehensive platform, for deploying, operating, and optimizing containerized applications across clouds, powered by Kubernetes. Nirmata empowers enterprise DevOps teams by fully automating the complex operations and management of application containers and its underlying ...
    SYS-CON Events announced today that Opsani to exhibit at SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California. Opsani is creating the next generation of automated continuous deployment tools designed specifically for containers. How is continuous deployment different from continuous integration and continuous delivery? CI/CD tools provide build and test. Continuous Deployment is the means by which...