In our April 2005 issue (Persistence Storage with EJB, page 104) we had demonstrated an entity bean application. The application stored data (there were four rows of data) in the table 'bank' using a container-managed persistence. That table consisted of three fields (name, id and department). In this article we will demonstrate querying and fetching of records from the same table. We will also show how to fetch records for 'id' greater than 101.
In order to do this, the home interface and client classes need modification and we also need to recreate our deployment
descriptors files. There is no change in the remote interface and the bean class. The modified home interface and client class files are given on this month's PCQEssential CD.
The new home interface
A finder method is now added to the home interface. The home interface can have multiple finder methods. As per the J2EE specification, this method should have the prefix find, return type as either collection interface or remote interface and throw finder and remote exceptions as shown in the code below.
|
public Collection findId(String fid) throws FinderException, RemoteException
Client
The method find_id_greater is added to the client that calls the 'findId' method of the home interface and fetches the records from the table through the 'Iterator' interface.
public void find_id_greater_101(String s)throws RemoteException, FinderException{
Collection c = home.findId(s);
if(c.isEmpty()){
log("No id greater than 101 found");
}
Iterator it = c.iterator();
while (it.hasNext()) {
Bank b = (Bank) PortableRemoteObject.narrow(it.next(), Bank.class);
log("Id" + " " + b.getId() + " " + "name is " + b.getName());
}
}
Deployment descriptor
Compile the home, remote and bean classes and create the .jar file. Also ensure that a new connection pool and data source are created. Open the .jar file in the WebLogic Builder and make the required entries. For all these three steps, refer to our article in the April 2005 issue. Give the JNDI name under the General tab as
'bank_june'.
Take care to enter the new JNDI name of the data source under 'Container Managed Persistence'. Click on Finders on the left-side pane. Select the findId(java.lang.String) below the Method label and click on Edit on the right-side pane. In '* EJB QL: window' add the query as:
SELECT OBJECT(o) FROM BankBean AS o where o.id > ?1
The query will fetch records for id's greater than 101. The value 101 is passed to findId method in the client. Click on OK and go to Tools>Validate Descriptor, 'ejbc successful' message will be displayed. Click on File>Save. Deploy the application in the WebLogic server as before. Start the Point Base Server.
Running the client
Copy the client in the bank folder and run the command.
C:\bank> javac -d . Client.java
C:\bank>java com.bank.Client
The output will be as follows.
Id 102 name is gyan
Id 103 name is rishi
Sushil Oswal