J2EEOnline J2EE





Entity Beans  «Prev  Next»
Lesson 2 Creating an entity bean instance
ObjectiveWrite the code to create an entity bean instance.

Connecting to the home object in J2EE

Entity beans must connect to the home object of the container before the bean can be created or manipulated. This process is exactly the same with the session beans that we looked at in the first course. The name of the JNDI context from the Customer bean is "MyCustomer." The code to connect to the home object is as follows:

Context initial = new InitialContext();
Object objref = initial.lookup("MyCustomer"); 

CustomerHome home =  (CustomerHome)PortableRemoteObject.narrow(objref, CustomerHome.class);
. . . 

Creating a new entity

The entity bean maps to the underlying persistent data. To create some persistent data, such as a new customer, the client creates a new instance of the Customer bean. The new instance automatically creates the underlying data. In practice, the persistent data may be created by another application or bean. You should only create a bean when your client is responsible for creating a new entity object.
The code in the client is very similar to the creation of session beans. In this case the bean instance and the underlying row are created. The row contains only the custnum. The name is not set yet. The create() method returns the remote reference to the just-created EJBObject of the instance, called mickey in the example below.



The Home interface for an entity bean contains one or more create methods.

Customer mickey = home.create("111");

import javax.ejb.CreateException;
import java.rmi.RemoteException;
import javax.ejb.*;
import java.util.*;

public interface CustomerHome extends EJBHome {
  public Customer create(String custnum) 
  throws CreateException, RemoteException;
  public Customer findByPrimaryKey(String primaryKey) 
	throws FinderException, RemoteException;
}

The next lesson will discuss, How to find an entity object by using its primary key?