Entity Beans

Entity beings? No, beans. Learn to write 'em, connect 'em to a database and access 'em via their cousin, the session bean.
Deployment Descriptor

Now that we have defined our entity bean, we need to describe it to the EJB container. Our deployment descriptor, a file named ejb-jar.xml, is shown in Listing 5. We place ejb-jar.xml in $BOOK/il/co/lerner/book/, alongside the Java classes that will form our entity bean; when we build the bean with Ant, it will be placed in a subdirectory named META-INF.

Listing 5. ejb-jar.xml, the Deployment Descriptor for Our Entity Bean

The most interesting parts of ejb-jar.xml for an entity bean are the <persistence-type> section (set to “Container” for CMP), the <prim-key-field> and <prim-key-class> sections (in which we name the class of our primary key), and the <cmp-field> sections (which describe the container-managed fields to JBoss).

The deployment descriptor is a standard part of EJB and should work across all EJB servers and containers. However, it does not address all of the runtime configuration issues. For JBoss to work correctly, we thus include a file named jboss.xml that tells the server where we can find the beans on the network. A copy of jboss.xml, which we place alongside ejb-jar.xml in $BOOK/il/co/lerner/book/, is shown here:

<?xml version="1.0" encoding="UTF-8"?>
<jboss>
  <enterprise-beans>
    <entity>
      <ejb-name>Book</ejb-name>
      <jndi-name>Book</jndi-name>
    </entity>
  </enterprise-beans>
</jboss>
Application

The source code for our simple test application, UseBook.java, is presented in Listing 6 [available at ftp.linuxjournal.com/pub/lj/listings/issue93/5577.tgz] and demonstrates how much you can do with very little code. It defines only a main() method and immediately goes about working with the EJBs. First it grabs a JNDI context and looks up the Book bean that we have defined. That allows it to create an instance of BookHome, which in turn lets us create a new instance of our Book bean:

Book book = home.create(testPrimaryKey, "Book title",
                        "AuthorFirst AuthorLast",
                        "PublisherName", 10.50);

As you can see, we've hard-coded the values we will add to the database, including the primary key. This is obviously unacceptable in the real world; a nonexample application would have taken the primary key (and other values) from a file, the command line, an environment variable, an HTML form on the Web or would have generated them automatically.

Notice how we never have to create SQL tables, insert rows or retrieve them. Our back-end persistent storage is presumably a relational database, but our Java client neither knows nor cares.

Once it has inserted a new row into the table, UseBook modifies some of its values (by setting instance variable values) and then retrieves all of the instances of Book in the database (with findAll()). Along the way, it sends status messages to System.out, which are printed on the console.

Ant Configuration File

We use Ant, the Java replacement for the standard make program, to compile and install our program. Listing 7 [available at ftp.linuxjournal.com/pub/lj/listings/issue93/5577.tgz] shows our build.xml file, which compiles each of the .java source files from $BOOK/il/co/lerner/book, turns them into a jar file along with the deployment descriptor and JBoss runtime configuration file, and then installs the files into the JBOSS directory. If Ant is installed in ANT, you can compile all of the files, install them into the JBoss “deploy” directory and invoke UseBook.main() with:

$ANT/bin/ant use-book-ejb

As soon as JBoss notices the new (or updated) jar file, you will see output on the screen indicating what the server is doing. The output from Ant, by contrast, will display all of the items sent to System.out from within main(), including the status messages in Listing 6 that indicate what we have done. Each time you compile and run main() with a new ID value, a new row will be inserted into the database table.

Is EJB the Future?

Sun would like you to believe that EJB is the future of all server-side web applications. Microsoft, of course, is doing its utmost to convince you that .NET is the real future. How do independent developers fare in this war of giants, and what should free software advocates do?

The good news is that J2EE is an excellent architecture and philosophy. It's neither the most elegant nor the most flexible, and it does lock you into a single language. But overall, I'm impressed with J2EE and see it as an important milestone in the world of web application programming.

Unfortunately, there are a number of issues with J2EE that arise every time I use it to write an application. The first issue is that neither Java nor J2EE are open source, despite the fact that Java is free of charge and JBoss is licensed under the LGPL. Sun generally has been an honest player, but they are a commercial company with their own interests. Open-source advocates should not be surprised if and when Sun restricts the use of code or specifications.

In addition, the departure of Enhydra Enterprise appears to leave JBoss as the only open-source J2EE application server on the market. JBoss isn't officially certified as J2EE-compliant, however, because the JBoss team cannot pay for official certification. This strikes me as rather shortsighted of Sun; perhaps they could offer free or inexpensive certification for servers released under the GPL or LGPL, which (unlike the Berkeley license) ensure that no company could ever turn a certified server into a proprietary product. Official J2EE certification isn't important to me, but there are many CEOs and CTOs who do require it, which means that JBoss is often ignored for no good reason.

Java and EJB are complex, and it will take time for a programmer to learn about them. But the complexity of Java and EJB programming is dwarfed, in my experience, by a confusing array of configuration files, new terms, environment variables and other items that are unique to Java. Better documentation would certainly help, but it seems to me that a Java analogue to CPAN, which would make server-side Java configuration easier, would let programmers concentrate on programming rather than system maintenance issues.

Finally, the one part of .NET that really appeals to me is its relative openness to different programming languages. By definition, J2EE requires Java, which is often the right choice but should never be the only choice. SOAP and XML-RPC make it possible to bridge the gap between languages but without the nice transactioning and object-relational mapping that EJB brings to the table. For now, it seems that the only way for Python to speak to EJB is via SOAP or XML-RPC (or Jython), but I would love to see other possibilities in the future.

______________________

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

ejb

jagruti's picture

can anyone help to write code for jsp entering bookname and displaying authorname from schema using ejb strut
how to connect jsp to session bean and further to entity bean and all configuration of jbosstomcat4.1

Re: At the Forge: Entity Beans

Anonymous's picture

Experienced database programmers know that primary keys should be hidden from view,

I don't agree with this. How would we identify the entities then?
The primary key is the set of attributes that identifies the entity, and this means that it has to be visibale.

and most databases have a way to automate this; PostgreSQL's SERIAL type, MySQL's AUTO INCREMENT and Oracle's sequences are common solutions to this problem.

Those are only artificial primary keys. You can run into few problems when you wnat to use them.
For example you can't be sure what key belongs to the entity you have currently written into the table, because if the primary key is given by the database. If the written row has no primary key except the assigned one you can't even select by the attributes to get the ID, because you can get multiple rows as the response and then the bet is only way to decide. If you have multiple concurent writes it gets even worse.

Unfortunately, there is no easy way to use such automatically generated primary keys within EJB.

UID object from java.rmi.server can give you primary key.
It is a bit strange (out of sequence) but unique, and that is what counts.

Re: At the Forge: Entity Beans

Anonymous's picture

Where to get the database schema for this example ? thanks

White Paper
Linux Management with Red Hat Satellite: Measuring Business Impact and ROI

Linux has become a key foundation for supporting today's rapidly growing IT environments. Linux is being used to deploy business applications and databases, trading on its reputation as a low-cost operating environment. For many IT organizations, Linux is a mainstay for deploying Web servers and has evolved from handling basic file, print, and utility workloads to running mission-critical applications and databases, physically, virtually, and in the cloud. As Linux grows in importance in terms of value to the business, managing Linux environments to high standards of service quality — availability, security, and performance — becomes an essential requirement for business success.

Learn More

Sponsored by Red Hat

White Paper
Private PaaS for the Agile Enterprise

If you already use virtualized infrastructure, you are well on your way to leveraging the power of the cloud. Virtualization offers the promise of limitless resources, but how do you manage that scalability when your DevOps team doesn’t scale? In today’s hypercompetitive markets, fast results can make a difference between leading the pack vs. obsolescence. Organizations need more benefits from cloud computing than just raw resources. They need agility, flexibility, convenience, ROI, and control.

Stackato private Platform-as-a-Service technology from ActiveState extends your private cloud infrastructure by creating a private PaaS to provide on-demand availability, flexibility, control, and ultimately, faster time-to-market for your enterprise.

Learn More

Sponsored by ActiveState