Chapter 9 Creating Enterprise JavaBean Clients


Instantiating remote interface proxies

Use the home interface create and finder methods to create proxies for session Beans and entity Beans.

Instantiating proxies for a session Bean

A session Bean's home interface can have several create methods. Each creates an instance with different initial-value criteria. The fragment below shows a typical call:

try {
Inventory inv = invHome.create();
} catch (CreateException ce)
{
System.out.println("Create Exception:"
+ ce.getMessage());
}

Instantiating proxies for an entity Bean

Each instance of an entity Bean represents a row in an underlying database table. An entity Bean's home interface may contain both finder methods and create methods.

Finder methods Finder methods return instances that match an existing row in the underlying database.

A home interface may contain several finder methods, each of which accepts parameters that constrain the search for matching database rows. Every entity Bean home interface has a findByPrimaryKey method that accepts a structure that represents the primary key for a row to look up.

Finder methods throw javax.ejb.FinderException if no rows match the specified search criteria.

Create methods Create methods insert a row into the underlying database.

When instantiating an entity Bean proxy, call a finder method first if you are not sure whether an entity Bean's data is already in the database. Create methods throw a javax.ejb.CreateException exception if you attempt to insert a duplicate database row.

Example: instantiating an Entity Bean This example instantiates an Entity bean that represents a customer credit account. The primary key class has two fields: custName is a string and creditType is also a string. The example looks for a customer named Morry using the findByPrimaryKey method. If FinderException is thrown, the example calls a create method to create a new entity for customer Morry:

String _custName = "Morry";
String _creditType = "VISA";

custCreditKey custKey = new custCreditKey();
custKey.custName = _custName;
custKey.creditType = _creditType;
custMaintenance cust;try {
System.out.println(
"Looking for customer " + _custName);
cust = custHome.findByPrimaryKey(custKey);
} catch (FinderException fe) {
System.out.println(
"Not found. Creating customer " + _custName);
try {
cust = custHome.create(_custName, 2000);
} catch (CreateException ce)
System.out.println(
"Error: could not create customer "
+ _custName);
}
}

 


Copyright © 2000 Sybase, Inc. All rights reserved.