Entity Beans

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

Our entity bean models a single book, where each book has a title, an author, a publisher and a price. For the sake of simplicity and space, we will ignore the possibility that a book might have multiple authors or publishers. We also will avoid normalizing the data, which would mean having instance variables that are themselves entity beans.

We begin by implementing the BookBean class, depicted in Listing 1 [available at ftp.linuxjournal.com/pub/lj/listings/issue93/5577.tgz]. BookBean is a typical simple bean class definition for a container-managed entity bean; it defines a field for each column in the database that we want to trace, including an integer “id” field that serves as a primary key.

We must define the ejbCreate() method to match the signature of the create() method on the home interface. Each time someone invokes create() on the home interface, the EJB container invokes ejbCreate() on our bean class with the same arguments. ejbCreate() is where the real creation action is; while a CMP entity bean doesn't need to worry about handling the object-relational mapping, it does need to set its instance variables to appropriate values.

Other than ejbCreate(), the only methods we must write are the “getter” and “setter” methods for each field, such that other objects can retrieve or modify the field's value. Each method is pretty simple in our example, returning or modifying the value of an instance variable.

Our remote interface, shown in Listing 2, is called Book.java, and its API is almost identical to the bean class. Applications normally will talk to the remote interface; if something goes wrong, it throws a RemoteException.

Listing 2. Source code for our remote interface, Book.java—this class mirrors the public methods defined by our BookBean class.

We also define a home interface, shown in Listing 3, with a create() method that creates a new instance of Book (and implicitly, a new row in our database table) when handed all of a book's details. If we were so inclined, we could offer users multiple versions of create(), each of which would take a different number of arguments.

Listing 3. Defining a Home Interface

Notice how our create() method requires that we provide an explicit primary key. Experienced database programmers know that primary keys should be hidden from view, 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. Unfortunately, there is no easy way to use such automatically generated primary keys within EJB. Therefore, we must set it explicitly (as in this month's examples) or use an external value, such as the ISBN, which could be a String. This is one of the most surprising things that I've found about EJB, and I hope that future versions of the specification will remedy the situation.

The findBy...() methods allow us to locate and retrieve instances of Book. Invoking findByPrimaryKey(5) returns an instance of Book with the primary key 5. All of the findBy...() methods are implemented by the EJB container, saving us from having to do so ourselves. The findAll() method returns a collection of all objects of this type (i.e., all rows in the database table), allowing you to iterate through them.

Unfortunately, automatically defined findAll...() methods use simple equality checks. We cannot use regular expressions or other techniques to search for books whose author field begins with O, or whose publisher begins with A and ends with M. Instead, we must use findAll(), iterating through the returned collection and filtering through them as necessary.

Finally, our primary key class (BookPK.java), shown in Listing 4, defines a single instance variable (id) that acts as our primary key. The equals() method indicates whether two instances of BookPK are identical, allowing the system to compare two instances of Book. The hashCode() method must return a unique value for each instance, which can be the id in this particular case. The toString() method must return a string version of the primary key, which simply returns String.valueOf(id) in our class.

Listing 4. BookPK.java, the Primary Key Class for Our Entity Bean

Because all four of these classes are in the il.co.lerner.book package, I placed all four source files (Book.java, BookBean.java, BookHome.java and BookPK.java) in the directory $BOOK/il/co/lerner/book, where BOOK is the root directory of this project.

______________________

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